CI/CD with Docker

Continuous Integration and Continuous Deployment (CI/CD) with Docker enables faster, consistent, and automated software delivery. Integrating Docker into CI/CD pipelines ensures consistent environments across development, testing, and production.


Why Use Docker in CI/CD?

  • Build once, run anywhere — eliminate environment inconsistencies
  • Test in isolated containers for reliability
  • Speed up deployment using prebuilt images
  • Improve rollback capabilities with image versioning

Integrating Docker with Jenkins

Example Jenkins pipeline (Declarative syntax):

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh 'docker build -t myapp:latest .'
            }
        }
        stage('Test') {
            steps {
                sh 'docker run --rm myapp:latest npm test'
            }
        }
        stage('Push') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'docker-hub-creds',
                                                 usernameVariable: 'USER',
                                                 passwordVariable: 'PASS')]) {
                    sh 'echo $PASS | docker login -u $USER --password-stdin'
                    sh 'docker push myapp:latest'
                }
            }
        }
    }
}

Using Docker with GitHub Actions

Basic workflow to build and push Docker images:

name: CI

on:
  push:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3

    - name: Log in to Docker Hub
      uses: docker/login-action@v2
      with:
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_PASSWORD }}

    - name: Build and push
      uses: docker/build-push-action@v3
      with:
        push: true
        tags: myapp:latest

GitLab CI/CD with Docker

Sample .gitlab-ci.yml file for Docker builds:

image: docker:latest

services:
  - docker:dind

variables:
  DOCKER_DRIVER: overlay2

stages:
  - build
  - deploy

build_image:
  stage: build
  script:
    - docker build -t myapp .
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker push myapp

Best Practices for Docker CI/CD

  • Tag images with build numbers or Git SHA for traceability
  • Run tests inside containers for consistency
  • Use lightweight base images to speed up builds
  • Scan Docker images as part of the pipeline
  • Push only signed or verified images to production registries

Docker enables standardized, reproducible workflows in CI/CD. Whether using Jenkins, GitHub Actions, or GitLab, integrating Docker enhances deployment agility and environment parity.