Chapter 12.2 - CI/CD with Kubernetes
Learning Objectives
By the end of this chapter, you will be able to:
- Understand CI/CD pipelines for Kubernetes
- Configure GitHub Actions for Kubernetes
- Implement GitLab CI/CD
- Use GitOps with ArgoCD
- Automate deployments
- Implement deployment strategies
Introduction
CI/CD pipelines automate the build, test, and deployment of applications in Kubernetes.
GitHub Actions
Basic Pipeline
name: Deploy to Kubernetes
on:
push:
branches: [main]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build Docker image
run: |
docker build -t my-app:${{ github.sha }} .
docker tag my-app:${{ github.sha }} my-registry/my-app:${{ github.sha }}
- name: Push to registry
run: |
echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
docker push my-registry/my-app:${{ github.sha }}
- name: Deploy to Kubernetes
uses: azure/k8s-deploy@v4
with:
manifests: |
k8s/deployment.yaml
k8s/service.yaml
images: |
my-registry/my-app:${{ github.sha }}
kubectl-version: 'latest'
GitLab CI/CD
.gitlab-ci.yml
stages:
- build
- test
- deploy
build:
stage: build
script:
- docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
- docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
test:
stage: test
script:
- docker run $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA npm test
deploy:
stage: deploy
script:
- kubectl set image deployment/my-app app=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
only:
- main
GitOps with ArgoCD
Installation
# Install ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
ArgoCD Application
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: my-app
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/user/my-app
targetRevision: main
path: k8s
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true
selfHeal: true
syncOptions:
- CreateNamespace=true
Deployment Strategies
Rolling Update
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
Blue/Green
Deploy a new version in parallel, then switch traffic.
Canary
Gradually deploy to a percentage of users.
Best Practices
1. Automated Tests
Run tests before each deployment.
2. Environments
Separate dev, staging, production.
3. Approvals
Require approvals for production.
4. Rollback
Have a fast rollback plan.
5. Monitoring
Monitor deployments in real time.
Summary
In this chapter, you learned:
CI/CD: Automation of build, test, and deployment
GitHub Actions: Integrated CI/CD pipelines
GitLab CI: Pipelines with .gitlab-ci.yml
GitOps: ArgoCD for declarative deployments
Strategies: Rolling, Blue/Green, Canary
Best practices: Tests, environments, approvals, rollback
Next Steps
Chapter 12.3: Environments
Lab 12.2: Horizontal and Vertical Autoscaling
Lab 12.3: GitOps with ArgoCD
Chapter created on: December 2024