Deploy to Kubernetes from GitLab CI

GitLab CI configuration for deploying applications to Kubernetes clusters. Covers kubectl apply, Helm chart deployments, and environment management.

Deployment

Detailed Explanation

Deploying to Kubernetes from GitLab CI

GitLab CI integrates well with Kubernetes for automated deployments. This configuration covers both raw kubectl and Helm-based approaches.

kubectl Deployment

stages:
  - build
  - deploy

variables:
  KUBE_NAMESPACE: my-app

deploy_staging:
  stage: deploy
  image: bitnami/kubectl:1.29
  before_script:
    - kubectl config set-cluster k8s --server=$KUBE_SERVER --certificate-authority=$KUBE_CA
    - kubectl config set-credentials deployer --token=$KUBE_TOKEN
    - kubectl config set-context default --cluster=k8s --user=deployer --namespace=$KUBE_NAMESPACE
    - kubectl config use-context default
  script:
    - envsubst < k8s/deployment.yaml | kubectl apply -f -
    - kubectl rollout status deployment/my-app --timeout=120s
  environment:
    name: staging
    url: https://staging.example.com
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

Helm Deployment

deploy_helm:
  stage: deploy
  image: alpine/helm:3.14
  before_script:
    - helm repo add bitnami https://charts.bitnami.com/bitnami
    - helm repo update
  script:
    - helm upgrade --install my-app ./helm/my-app
        --namespace $KUBE_NAMESPACE
        --set image.tag=$CI_COMMIT_SHA
        --set replicaCount=3
        --wait --timeout 5m
  environment:
    name: production
    url: https://app.example.com
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: manual

Environment Management

The environment keyword creates environment tracking in GitLab, showing which commit is deployed to each environment. The url enables a "View deployment" button in the GitLab UI.

Rollback Strategy

rollback:
  stage: deploy
  image: bitnami/kubectl:1.29
  script:
    - kubectl rollout undo deployment/my-app -n $KUBE_NAMESPACE
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: manual
  environment:
    name: production
    action: stop

Security Considerations

  • Store KUBE_TOKEN and KUBE_CA as masked CI/CD variables.
  • Use a service account with minimal RBAC permissions.
  • Never log the kubeconfig or token values.

Use Case

Use for deploying containerized applications to Kubernetes clusters, whether managed (GKE, EKS, AKS) or self-hosted. The Helm approach is preferred for complex applications with multiple configuration values.

Try It — GitLab CI Config Generator

Open full tool