Skip to main content

Gitlab CI - build docker images

We can use CI/CD pipeline to help us build a docker image after we have merged the codes into the main/master branch. In addition, we can combine the service of watchtower to automatically pull/update our docker image for our service. It is very handy and save our time. :P

The concept is to build a docker image in the docker env, that we call "Docker-in-Docker (dind)".

The .gitlab-ci.yml setting is simple.

Major components:

  1. You can use "services"

    services:
    - docker:dind

    However, if we do not use it, it can still work. And I also found that the time of CI processing is faster.

  2. The docker image needs to use "docker"; for example, image: docker:19.03.15-git.

  3. In the job, we need to set a before_script parameter to login the docker registry.

    before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  4. We can set variables to easily re-use in the job.

    variables:
    IMAGE_NAME: test-image
    CI_IMAGE: $CI_REGISTRY_IMAGE/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA
  5. In the CICD pipeline, we can add "--cache-from=" to speed up the building image time.

    script:
    - docker build --cache-from=$IMAGE_NAME -t $CI_IMAGE .

For example:

  • $CI_REGISTRY_USER: user account name
  • $CI_REGISTRY_PASSWORD: password
  • $CI_REGISTRY_IMAGE: normally it is your <domain ip/name> with repository name such as registry.gitlab.com/<owner>/<project>
  • $IMAGE_NAME: additional name
  • $CI_COMMIT_SHORT_SHA: commit node
.gitlab-ci.yml
stages:
- build

services:
- docker:dind

variables:
IMAGE_NAME: test-image
CI_IMAGE: $CI_REGISTRY_IMAGE/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA

buildImages:
image: docker
stage: build
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
tags:
- linux
script:
- echo "Start to build a docker image."
- docker build -t $CI_IMAGE .
- docker push $CI_IMAGE
rules:
- if: $CI_COMMIT_BRANCH == "build_docker_image"
  1. we can set the default image and tag like below.
  2. we dont need to fill out the docker image and tag information in each job via the default area.
  3. If you dont add the "service", it will work well. Also, we can add "--cache-from=" to speed up the building image time.
.gitlab-ci.yml
default:
image: docker:19.03.15-git
tags:
- linux

stages:
- build

services:
- docker:dind

variables:
IMAGE_NAME: test-image
CI_IMAGE: $CI_REGISTRY_IMAGE/$IMAGE_NAME:$CI_COMMIT_SHORT_SHA

buildImages:
stage: build
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
script:
- echo "Start to build a docker image."
- docker build --cache-from=$IMAGE_NAME -t $CI_IMAGE .
- docker push $CI_IMAGE
rules:
- if: $CI_COMMIT_BRANCH == "build_docker_image"