Skip to content

Building multiple docker images

This document explains how to use the GitLab multi-target Docker build template in your CI/CD pipelines to allow building multiple docker images in a single repository.

Overview

This template allows for building and publishing multi target Docker images. It addresses common challenges when building multiple docker images – such as avoiding duplicated steps and streamlining image management – and enables parallel builds of multiple Docker image targets via GitLab child pipelines. It triggers a downstream pipeline where jobs run based on a matrix of Docker build targets. For more details, refer to this GitLab CI template.

Configuration and Usage

This template is meant to be used in conjunction with the common pipeline. When using this template, it is expected to pass the docker_build_targets input argument containing the Docker stages you want to build.

The following example demonstrates how to include this template and build two specific targets. Using the example Dockerfile:

FROM golang:1.23 AS base
WORKDIR /src
COPY <<EOF /src/main.go
package main

import "fmt"

func main() {
  fmt.Println("hello, world")
}
EOF

FROM base AS build
RUN go build -o /bin/hello ./main.go

FROM base AS development
CMD ["go", "run", "main.go"]

FROM scratch AS production
COPY --from=build /bin/hello /bin/hello
CMD ["/bin/hello"]

You would include the template as:

include:
  - project: "uis/devops/continuous-delivery/ci-templates"
    file: "/auto-devops/multi-target-docker-images.gitlab-ci.yml"
    inputs:
      docker_build_targets: ["development", "production"]

Which would build both the "development" and "production" stage.

Note: This configuration disables the build for the final stage unless it is explicitly included in docker_build_targets.

Additional Configuration Details

Building the Final Target

Without any additional configuration the final stage build will be disabled. In order to re-enable this add the following to your variables:

variables:
  # Override variables set by the multi target docker images template, as we do want to build the
  # final stage but we don't want to explicitly tag it with the final stage name
  BUILD_DISABLED: ""
  CONTAINER_SCANNING_DISABLED: ""
  DISABLE_ARTIFACT_REGISTRY_PUSH: ""

This ensures the final build target is built in the main pipeline.

Disabling Specific Child Jobs

The template passes the MULTI_DOCKER_IMAGE_BUILD_ENABLED variable (set to "1") to the child pipelines. This variable can be used to determine whether a job is running in the child pipeline or the main pipeline. This can be useful to disable or enable certain jobs. For example, if you want to disable running tests in the child pipelines, you can add

variables:
  # We want to disable the tests in the multi target pipelines
  TEST_DISABLED: $MULTI_DOCKER_IMAGE_BUILD_ENABLED