Building and Tagging Container Images in Gitlab with Kaniko

Cloud TunedCloud Tuned
2 min read

Introduction

Building and tagging a container image in GitLab using Kaniko is performed by specifying the docker file Kaniko is suppose to use to build the container image and also by specifying the desired tags in the destination argument of the executor command within your GitLab CI/CD pipeline.

Steps to Tag a Kaniko-Built Image in GitLab CI/CD:

  • Define your Kaniko build job in .gitlab-ci.yml:

You will typically use the gcr.io/kaniko-project/executor:debug image for your build job, as it includes a shell necessary for GitLab CI/CD. Specify the destination with tags.

The --destination flag in the executor command is where you define the image name and its tags. You can include multiple tags by listing them separately.

    build_image:
      stage: build
      image:
        name: gcr.io/kaniko-project/executor:debug
        entrypoint: [""] # Override the entrypoint for GitLab CI/CD compatibility
      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_SHA --destination $CI_REGISTRY_IMAGE:latest

In this example:

  • $CI_REGISTRY_IMAGE refers to the image name in your GitLab Container Registry.
  • $CI_COMMIT_SHA automatically tags the image with the Git commit SHA.
  • :latest adds the latest tag to the same image.

  • Authentication (if pushing to a private registry):

Kaniko requires authentication to push to private registries like the GitLab Container Registry. This is typically achieved by mounting a config.json file containing the registry credentials. The example above demonstrates how to create this config.json using GitLab CI/CD predefined variables ($CI_REGISTRY, $CI_REGISTRY_USER, $CI_REGISTRY_PASSWORD).

Considerations for Tagging:

  • Meaningful Tags:

    Use tags that clearly indicate the image's version, build context (e.g., commit SHA, branch name), or purpose (e.g., latest, stable, dev).

  • Multiple Tags:

    You can apply multiple tags to a single image, allowing for flexibility in referencing specific versions or the most recent stable build.

  • Automated Tagging:

    Leverage GitLab CI/CD variables (e.g., $CI_COMMIT_REF_NAME, $CI_COMMIT_TAG, $CI_COMMIT_SHORT_SHA) to automate tag generation based on your repository's state.

0
Subscribe to my newsletter

Read articles from Cloud Tuned directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Cloud Tuned
Cloud Tuned