Skip to content
Latchkey

How to Build and Push a Docker Image in GitLab CI

GitLab gives every project a container registry and CI variables to push to it from a build job.

Use the docker:dind service (or Kaniko for rootless) and log in with the predefined CI_REGISTRY* variables. The registry image path is $CI_REGISTRY_IMAGE.

Build with Docker-in-Docker

Log in with the CI job token, then build and push tagged at the commit SHA.

.gitlab-ci.yml
build-image:
  image: docker:27
  services:
    - docker:27-dind
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
  script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
    - docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .
    - docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"

Gotchas

  • The docker:dind service plus matching client image: versions are required; mismatched versions break the build.
  • Use the predefined $CI_REGISTRY_USER/$CI_REGISTRY_PASSWORD (job token) - no need to store registry creds yourself.
  • On runners without privileged mode, use Kaniko (gcr.io/kaniko-project/executor) instead of dind.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →