Docker Build and Push in GitLab CI

GitLab CI configuration for building Docker images and pushing to GitLab Container Registry. Covers Docker-in-Docker setup, multi-stage builds, and tag strategies.

Docker & Containers

Detailed Explanation

Docker Build & Push Pipeline

Building and pushing Docker images is one of the most common GitLab CI use cases. This configuration handles the Docker-in-Docker (DinD) setup and implements a smart tagging strategy.

Pipeline Configuration

stages:
  - build
  - push

variables:
  DOCKER_HOST: tcp://docker:2376
  DOCKER_TLS_CERTDIR: /certs
  DOCKER_DRIVER: overlay2

docker_build:
  stage: build
  image: docker:24
  services:
    - name: docker:24-dind
      alias: docker
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  tags:
    - docker

docker_tag_latest:
  stage: push
  image: docker:24
  services:
    - name: docker:24-dind
      alias: docker
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    - docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:latest
    - docker push $CI_REGISTRY_IMAGE:latest
  needs:
    - docker_build
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

Docker-in-Docker Setup

The docker:24-dind service runs a Docker daemon inside the CI job container. The main job connects to it via tcp://docker:2376 with TLS. The DOCKER_TLS_CERTDIR variable enables encrypted communication between the client and daemon.

Tag Strategy

  • $CI_COMMIT_SHA: Every build gets a unique, immutable tag tied to the exact commit. This enables precise rollbacks.
  • latest: Only updated on the main branch. This is the default tag pulled by deployments.

GitLab Container Registry

GitLab provides a built-in container registry. The predefined variables $CI_REGISTRY, $CI_REGISTRY_USER, and $CI_REGISTRY_PASSWORD are automatically available in every CI job, requiring no manual configuration.

Use Case

Use this configuration when your project has a Dockerfile and you want to automatically build and publish Docker images on every push. The images are stored in GitLab's built-in container registry.

Try It — GitLab CI Config Generator

Open full tool