Continuous Integration (CI) and Continuous Deployment (CD) are essential practices in modern software development that help automate the process of testing and deploying applications. In this lesson, you will learn how to integrate CI/CD pipelines with Kubernetes for automated application updates.
A CI/CD pipeline typically consists of several stages: 1. Source Code Management: Code is pushed to a version control system (e.g., Git). 2. Build: The application is built into a container image. 3. Test: Automated tests are run to ensure code quality. 4. Deploy: The application is deployed to a Kubernetes cluster.
In this example, we will use GitHub Actions to create a CI/CD pipeline that builds a Docker image and deploys it to a Kubernetes cluster.
Create a Dockerfile in your application directory:
# Dockerfile
FROM node:14
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]
Create a directory .github/workflows in your project and add a file named ci-cd.yml:
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Build Docker image
run: |
docker build -t myapp:${{ github.sha }} .
- name: Push Docker image
run: |
echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
docker push myapp:${{ github.sha }}
deploy:
runs-on: ubuntu-latest
needs: build
steps:
- name: Set up Kubeconfig
run: |
echo "${{ secrets.KUBE_CONFIG }}" > kubeconfig
export KUBECONFIG=kubeconfig
- name: Deploy to Kubernetes
run: |
kubectl set image deployment/myapp myapp=myapp:${{ github.sha }}
kubectl rollout status deployment/myapp
You need to configure the following secrets in your GitHub repository:
- DOCKER_USERNAME: Your Docker Hub username.
- DOCKER_PASSWORD: Your Docker Hub password.
- KUBE_CONFIG: The base64 encoded kubeconfig file for accessing your Kubernetes cluster.
Common Mistakes: - Not configuring secrets properly, leading to failed deployments. - Forgetting to run tests before deploying, which can introduce bugs to production.
In this lesson, you have learned: - The basics of CI/CD and its importance in modern application development. - How to set up a CI/CD pipeline using GitHub Actions to automate the building and deployment of applications to Kubernetes. - Best practices for maintaining a robust CI/CD pipeline.
By following these practices, you can ensure a smoother development workflow and faster delivery of features to your users.