# 🇬🇧 Build quickly and host easily your Docker images with GitLab and GitLab CI

More and more I "dockerize" my tools for my continuous integration scripts and/or for my deployments on Kubernetes. The best way for me is to keep the building script of the images and the images in a same way, with the ability to "tag" easily my images. For that, I create a repository dedicated to my Docker image. The repository will host at least a Dockerfile and this .gitlab-ci.yml file

stages:
  - 🚧build-img

# when I merge on master
🐳build:latest:
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: [""]
  stage: 🚧build-img
  only:
    refs:
      - master
  script: |
    echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
    /kaniko/executor \
      --context $CI_PROJECT_DIR \
      --dockerfile $CI_PROJECT_DIR/Dockerfile \
      --destination $CI_REGISTRY_IMAGE:latest

# when I commit on my merge request
🐳build:mr:
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: [""]
  stage: 🚧build-img
  only:
    refs:
      - merge_requests
  script: |
    echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
    /kaniko/executor \
      --context $CI_PROJECT_DIR \
      --dockerfile $CI_PROJECT_DIR/Dockerfile \
      --destination $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG

# when I release a version
🐳build:tag:
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: [""]
  stage: 🚧build-img
  only:
    - tags
  script: |
    echo "{\"auths\":{\"$CI_REGISTRY\":{\"username\":\"$CI_REGISTRY_USER\",\"password\":\"$CI_REGISTRY_PASSWORD\"}}}" > /kaniko/.docker/config.json
    /kaniko/executor \
      --context $CI_PROJECT_DIR \
      --dockerfile $CI_PROJECT_DIR/Dockerfile \
      --destination $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME

All the environment variables are set by GitLab CI

And now, after a commit or a merge I gain my own docker registry (go the "Packages & Registries" menu of your projet or group). You can see an example of one my groups here: https://gitlab.com/groups/borg-collective/-/container_registries (opens new window).

** 👋Btw**, you can buils several images for a same project, you just need to use the word changes to avoid the build of all the images at every commit:

🐳build-ci-js:
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: [""]
  stage: 🚧build-img
  only:
    refs:
      - master
      - merge_requests
    changes:
      - ci-js/**/*
    # etc...

The whole example is here: https://gitlab.com/tanuki-workshops/earth/images/ci-tools/-/blob/master/.gitlab-ci.yml (opens new window)

Last Articles