Continuous Deployment (CD) is a software development practice where code changes are automatically deployed to production after passing automated tests. In this lesson, we will explore how to implement CI/CD pipelines to automate application deployment in Kubernetes.
CI/CD stands for Continuous Integration and Continuous Deployment. It involves: - Continuous Integration (CI): Merging code changes into a central repository frequently, where automated builds and tests run. - Continuous Deployment (CD): Automatically deploying every code change that passes tests to production.
To implement CI/CD in Kubernetes, we typically use tools like Jenkins, GitLab CI/CD, or GitHub Actions. In this example, we'll use GitHub Actions to create a simple CI/CD pipeline for a Kubernetes application.
Let's assume we have a simple Node.js application that we want to deploy to a Kubernetes cluster.
Create a file named .github/workflows/deploy.yml in your repository:
name: CI/CD Pipeline for Kubernetes
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
deploy:
runs-on: ubuntu-latest
needs: build
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up kubectl
uses: azure/setup-kubectl@v1
with:
version: 'latest'
- name: Deploy to Kubernetes
run: |
kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml
env:
KUBE_CONFIG_DATA: ${{ secrets.KUBE_CONFIG_DATA }}
Make sure you have the Kubernetes manifests ready in your repository under a k8s directory. Here's a sample deployment.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-node-app
spec:
replicas: 3
selector:
matchLabels:
app: my-node-app
template:
metadata:
labels:
app: my-node-app
spec:
containers:
- name: my-node-app
image: my-node-app:latest
ports:
- containerPort: 3000
And a sample service.yaml:
apiVersion: v1
kind: Service
metadata:
name: my-node-app
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 3000
selector:
app: my-node-app
Common Mistakes: - Not including tests in the CI/CD pipeline. - Hardcoding sensitive data in the repository. - Not rolling back in case of failed deployments.
Implementing CI/CD pipelines in Kubernetes allows for faster and more reliable application deployments. By automating the deployment process, teams can focus on developing features rather than managing releases.
deployment.yaml file and observe how it affects your application.