GitLab
min read

How to Integrate GitLab CI/CD and Kubernetes for Version Control

Discover how to integrate GitLab CI/CD and Kubernetes for efficient version control. Learn to streamline your DevOps workflow with GitLab CI/CD and Kubernetes.
Written by
Alok Gupta
Published on
17 January 2022

Modern software development demands efficient, automated deployment pipelines that can handle containerized applications at scale. GitLab CI/CD combined with Kubernetes provides a powerful solution for managing version control, continuous integration, and automated deployments.

This comprehensive guide will walk you through integrating these technologies to create a robust DevOps workflow. You'll learn how to set up automated Docker deployments, implement CI/CD best practices, and manage containerized applications effectively.

Understanding the Foundation

GitLab CI/CD serves as your automation engine, executing predefined pipelines whenever code changes occur. It handles continuous integration, automated testing, and deployment orchestration seamlessly.

Kubernetes acts as your container orchestration platform, managing containerized applications across clusters. It provides scalability, high availability, and efficient resource management for modern microservices architectures.

When integrated properly, GitLab and Kubernetes create a seamless flow from code commit to production deployment. Each git commit triggers a pipeline that can build Docker images, run automated tests, and deploy to different Kubernetes environments based on branch policies.

This integration enables automatic building, testing, and deployment of applications while maintaining version control throughout the entire DevOps process.

Prerequisites and Setup Requirements

Before diving into the GitLab Kubernetes integration, ensure you have the necessary components in place:

Required Infrastructure:

  • GitLab instance (GitLab.com or self-hosted)
  • Kubernetes cluster with appropriate permissions
  • Docker registry access for storing container images
  • Sufficient cluster resources and network policies

Development Environment:

  • kubectl for Kubernetes management
  • Docker for local testing and image building
  • Appropriate access credentials for your GitLab project
  • Sufficient cluster permissions for deployments

Cluster Configuration:

  • Ingress controllers for routing external traffic
  • Load balancers for service exposure
  • Persistent storage for stateful applications
  • Network policies for security and isolation

Suggested Read: The Ultimate CI/CD Security Checklist for GitLab Users

Configuring GitLab CI/CD Variables

GitLab CI/CD relies on environment variables to securely manage sensitive information like Kubernetes credentials and registry authentication. Navigate to your project's Settings > CI/CD > Variables section to configure these essential CI/CD pipeline variables.

Essential Variables to Configure:

  • Kubernetes API server URL
  • Authentication token for cluster access
  • Cluster certificate for secure communication
  • Docker registry credentials (username, password, URL)

Security Best Practices for Variables:

Mark sensitive variables as protected and masked

Use environment-specific prefixes (PROD_, STAGING_, DEV_)

  • Regularly rotate access tokens and credentials
  • Avoid exposing sensitive data in pipeline logs

This organization allows the same pipeline configuration to deploy to different environments based on git branch or manual triggers, maintaining a clear separation between deployment targets.

Creating the GitLab CI/CD Pipeline

The .gitlab-ci.yml file defines your CI/CD pipeline stages and jobs. A typical Kubernetes deployment pipeline includes build, test, package, and deploy stages for comprehensive automated deployment.

Each stage serves a specific purpose in transforming your source code into running applications. The build stage compiles your application and ensures code quality through automated testing.

The package stage creates Docker images and pushes them to your container registry with appropriate version tags. This enables consistent deployments and easy rollbacks across environments.

The deploy stage applies Kubernetes manifests to your cluster, creating or updating resources as needed. Version control integration happens through Git tags and commit SHAs, which become Docker image tags and Kubernetes resource labels.

stages:

 - build

 - test

 - package

 - deploy

variables:

 DOCKER_DRIVER: overlay2

 DOCKER_TLS_CERTDIR: "/certs"

build:

 stage: build

 image: node:16

 script:

   - npm install

   - npm run build

 artifacts:

   paths:

     - dist/

test:

 stage: test

 image: node:16

 script:

   - npm install

   - npm run test

 coverage: '/Coverage: \d+\.\d+%/'

package:

 stage: package

 image: docker:latest

 services:

   - docker:dind

 before_script:

   - echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY

 script:

   - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .

   - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA

 only:

   - main

   - develop

deploy:

 stage: deploy

 image: bitnami/kubectl:latest

 before_script:

   - kubectl config set-cluster k8s --server="$KUBE_URL" --certificate-authority="$KUBE_CA_PEM_FILE"

   - kubectl config set-credentials gitlab --token="$KUBE_TOKEN"

   - kubectl config set-context default --cluster=k8s --user=gitlab

   - kubectl config use-context default

 script:

   - envsubst < k8s-deployment.yaml | kubectl apply -f -

 environment:

   name: production

 only:

   - main

Kubernetes Deployment Manifests

Kubernetes deployment manifests define how your containerized applications run in the cluster through YAML files that specify resources, replicas, and configurations.

Key Manifest Components:

  • Resource requirements and limits for predictable performance
  • Health checks (liveness and readiness probes) for automatic recovery
  • Image pull policies and container specifications
  • ConfigMaps and Secrets for secure configuration management

Template manifests with environment variables to support multiple deployment environments. This enables consistent deployments across development, staging, and production.

Service manifests expose applications using ClusterIP (internal), LoadBalancer (external), or Ingress (HTTP routing) based on your networking requirements.

apiVersion: apps/v1

kind: Deployment

metadata:

 name: ${CI_PROJECT_NAME}

 labels:

   app: ${CI_PROJECT_NAME}

   version: ${CI_COMMIT_SHA}

spec:

 replicas: 3

 selector:

   matchLabels:

     app: ${CI_PROJECT_NAME}

 template:

   metadata:

     labels:

       app: ${CI_PROJECT_NAME}

       version: ${CI_COMMIT_SHA}

   spec:

     containers:

     - name: ${CI_PROJECT_NAME}

       image: ${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHA}

       ports:

       - containerPort: 8080

       resources:

         requests:

           memory: "64Mi"

           cpu: "250m"

         limits:

           memory: "128Mi"

           cpu: "500m"

       livenessProbe:

         httpGet:

           path: /health

           port: 8080

         initialDelaySeconds: 30

         periodSeconds: 10

       readinessProbe:

         httpGet:

           path: /ready

           port: 8080

         initialDelaySeconds: 5

         periodSeconds: 5

Implementing Version Control Strategies

Effective version control strategies ensure consistent deployments and easy rollbacks in your DevOps workflow. Use semantic versioning for release tags, creating clear relationships between code versions and deployed applications.

Implement branch-based deployment strategies where main branch deployments go to production, develop branch to staging, and feature branches to ephemeral environments. This approach provides a clear separation between different stages of development.

Tag Docker images with both commit SHAs and semantic versions to maintain traceability. This dual-tagging approach allows you to identify exactly which code version is running while also supporting easy rollbacks to previous stable releases.

Consider implementing blue-green deployments or canary releases for production updates. These deployment strategies use Kubernetes labels and selectors to gradually shift traffic between application versions.

Blue-green and canary deployments reduce deployment risks and enable quick rollbacks if issues arise. They're essential for maintaining high availability in production environments.

Security Best Practices for GitLab CI/CD and Kubernetes Integration

Security considerations are paramount when integrating CI/CD pipelines with Kubernetes clusters. Follow these essential security practices:

Access Control and Permissions:

  • Use dedicated service accounts with minimal required permissions
  • Implement RBAC (Role-Based Access Control) for cluster resources
  • Follow the principle of least privilege for all integrations
  • Regularly review and audit access permissions

Network Security:

  • Implement network policies to restrict inter-namespace communication
  • Use ingress controllers with proper TLS configuration
  • Limit external access to cluster resources
  • Configure firewall rules for cluster nodes

Secrets Management:

  • Store sensitive data in GitLab CI/CD variables (protected and masked)
  • Use Kubernetes Secrets for runtime configuration
  • Never hardcode secrets in deployment manifests or container images
  • Regularly rotate access tokens and API keys

Container Security:

  • Run containers as non-root users when possible
  • Implement Pod Security Standards across workloads
  • Use resource quotas to prevent resource exhaustion
  • Regularly scan container images for vulnerabilities

Monitoring and Compliance:

  • Enable audit logging for cluster activities
  • Monitor for suspicious activities and unauthorized access
  • Implement compliance checks in CI/CD pipelines
  • Maintain security documentation and incident response procedures

Monitoring and Debugging Your DevOps Pipeline

Effective monitoring is crucial for maintaining reliable GitLab Kubernetes deployments. Configure GitLab CI/CD to report deployment status and set up alerts for pipeline failures and application issues.

Essential Monitoring Components:

  • Real-time deployment status tracking in GitLab environments
  • Structured logging for both pipeline execution and application runtime
  • Kubernetes monitoring tools (Prometheus, Grafana) for performance metrics
  • kubectl debugging commands for troubleshooting common issues

Advanced Integration Patterns

As your GitLab Kubernetes integration matures, explore these advanced deployment strategies:

GitOps Workflows:

  • Store Kubernetes manifests in separate repositories
  • Use operators like ArgoCD or Flux for automatic manifest application
  • Enable declarative infrastructure management with improved audit trails

Progressive Delivery:

  • Implement multi-environment promotion workflows
  • Use feature flags and A/B testing for safer releases
  • Configure Horizontal Pod Autoscaling (HPA) and Vertical Pod Autoscaling (VPA)
  • Set up environment-specific variables and deployment approvals

Troubleshooting Common Issues

Pipeline failures often stem from various issues in your GitLab Kubernetes setup. Here are the most common problems and their solutions:

Authentication and Access Issues:

  • Verify GitLab CI/CD variable configuration is correct
  • Check Kubernetes cluster connectivity from GitLab runners
  • Ensure kubectl configuration has proper credentials
  • Validate service account permissions and RBAC settings

Image Pull and Registry Problems:

  • Verify Docker registry authentication credentials
  • Check that image tags match between build and deployment stages
  • Ensure the container registry is accessible from cluster nodes
  • Implement image pull secrets for private registries

Resource and Scheduling Issues:

  • Monitor cluster resource usage (CPU, memory, storage)
  • Adjust deployment resource requests and limits appropriately
  • Check node capacity and availability zones
  • Implement horizontal pod autoscaling for dynamic scaling

Configuration and Manifest Errors:

  • Validate YAML syntax in deployment manifests
  • Check the environment variable substitution in templates
  • Verify service and ingress configurations
  • Ensure ConfigMap and Secret references are correct

Network and Connectivity Problems:

  • Test DNS resolution within the cluster
  • Verify that network policies allow required communication
  • Check the ingress controller configuration and routing rules
  • Validate load balancer and service endpoint configurations

Conclusion

Integrating GitLab CI/CD with Kubernetes creates a powerful automated deployment platform that enables faster feature delivery while maintaining security and reliability standards.

Key Benefits:

  • Automated containerized deployments with version control
  • Scalable infrastructure that grows with your organization
  • Enhanced security through proper access controls and monitoring
  • Streamlined DevOps workflows from code to production

Start with simple deployment pipelines and gradually add complexity as your team becomes comfortable with the workflow. This integration evolves with your needs, supporting everything from simple applications to complex microservices architectures.

Need Help with GitLab CI/CD Implementation?

Setting up GitLab CI/CD and Kubernetes integration can be complex. If you need expert assistance with your DevOps pipeline implementation, VivaOps provides specialized GitLab CI/CD consulting services. Our team helps organizations optimize their deployment workflows, implement security best practices, and scale their containerized applications effectively.

Contact VivaOps today for professional GitLab CI/CD and Kubernetes integration support.

Join Our Newsletter
No spam. Just the latest releases and tips, interesting articles, and exclusive insights in your inbox.
Read about our privacy policy.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Experience the VivaOps Advantage

Unify, automate, and scale. Elevate your software delivery and performance.