Build and store Docker images with GitLab

Jun 27, 2022 by Thibault Debatty | 8492 views

GitLab Docker

https://cylab.be/blog/227/build-and-store-docker-images-with-gitlab

With GitLab, you can add a job to your pipeline to build Docker images, and push them to the built-in container registry. Here is how…

Prerequisites: for this to work, you will need a gitlab-runner with docker-in-docker configured, and a working Dockerfile.

Build job

Here is the job you can add to your .gitlab-ci.yml to build and save your docker image at each git push.

build:
  image: docker:20.10.16
  # run on a gitlab-runner that is configured with docker-in-docker
  tags:
    - dind
  stage: build

  services:
    - docker:20.10.16-dind

  variables:
    # use TLS https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#tls-enabled
    # mounts /certs directory for the service and build container
    # needed for the Docker client to use the certificates
    DOCKER_TLS_CERTDIR: "/certs"

  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY

  script:
    # use previous image as a cache to speedup build process
    - docker pull $CI_REGISTRY_IMAGE:latest || true
    # use the commit sha to tag the image
    - docker build --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA --tag $CI_REGISTRY_IMAGE:latest .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
    - docker push $CI_REGISTRY_IMAGE:latest

If all went wel, images will start to appear in the container registry of GitLab…

gitlab-container-registry.png

Build job for git tags

And here is a job to build the docker image only for git tags:

build:
  image: docker:20.10.16
  # run on a gitlab-runner that is configured with docker-in-docker
  tags:
    - dind
  stage: build
  # only for git tags
  only:
    - tags

  services:
    - docker:20.10.16-dind

  variables:
    # use TLS https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#tls-enabled
    # mounts /certs directory for the service and build container
    # needed for the Docker client to use the certificates
    DOCKER_TLS_CERTDIR: "/certs"

  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY

  script:
    # use previous image as a cache to speedup build process
    - docker pull $CI_REGISTRY_IMAGE:latest || true
    # use git tag to tag the image
    - docker build --cache-from $CI_REGISTRY_IMAGE:latest --tag $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG --tag $CI_REGISTRY_IMAGE:latest .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
    - docker push $CI_REGISTRY_IMAGE:latest

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.
Accept