Skip to content

GitLab CI component: build an image on the build farm

ci/gitlab/build.yml is a GitLab CI/CD component: one job that sends the build context to a BuildKit daemon of the build farm, which builds with the shared cache and pushes the image. The job itself only waits; it needs a runner set up by the box (or by integrations/gitlab-runner), which gives job pods BUILDKIT_REMOTE_ADDR and a client certificate.

In the box, BUILDKIT_REMOTE_ADDR is the build router (tcp://<release>-router.<namespace>.svc:1234): it sends the job to the node where its project built before, else to the project’s node by a hash every router agrees on, so the jobs of a pipeline share one daemon’s cache and steps. The job’s mutual TLS with the daemon passes through it. The console’s build page says which node built and why. Without the router, the job reaches the daemon on its own node.

What the job does for you:

  • logs in to GitLab’s registry and its Dependency Proxy (base images FROM ${CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX}/...) with the job token, and ignores DOCKER_AUTH_CONFIG, which would otherwise override that token for the same registry and break the push. On a GitLab without a container registry it builds without credentials (push: false) and refuses to push; other private registries need registry-auth: docker-auth-config;
  • passes secrets by the name of a CI/CD variable, never as build arguments; a File-type variable mounts the file’s content;
  • stops the build after timeout-minutes, and says so (buildctl has no keepalive of its own: a build node that disappears without closing the connection could hold the job until GitLab’s job timeout); a buildctl that has not stopped a minute later is killed;
  • prints how much context it sent and how many Dockerfile steps came from the cache;
  • hands the image digest to later jobs (IMAGE, IMAGE_DIGEST, IMAGE_REF as a dotenv report).
  • names its job to the box (the job’s TRACEPARENT, which the box’s runner sets, as the build option ci-accelerator.io/traceparent): the console shows the build live on the job’s page while it runs. BuildKit’s Dockerfile frontend ignores the option; no cache key sees it. A buildctl build of your own shows live with the same --opt "ci-accelerator.io/traceparent=$TRACEPARENT".

The first job step by step, with what to check before the push and what a cold and a cached run print: docs/first-build.md.

From GitHub, pinned to a release and checked by its hash (GitLab 17.9 or newer; without integrity, 17.0). Every release’s notes print this block with the hash filled in; use the release that matches your box, so the job’s BuildKit client matches the daemons:

include:
- remote: https://raw.githubusercontent.com/hoobiboobi/ci-accelerator/v0.6.0/ci/gitlab/build.yml
integrity: sha256-<from the release notes>
inputs:
runner-tags: [ci-accelerator]

That is the whole job for a Dockerfile at the repository root: it builds and pushes $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA. The GitLab server fetches the file when the pipeline starts, so it needs to reach GitHub. Without that, copy build.yml into a project of your GitLab and use include: project (or include: local); the file includes nothing else.

Add .git to .dockerignore: every job has a fresh clone, and with .git in the context every step after COPY . . runs again.

Several images of a monorepo, each its own job:

include:
- remote: https://raw.githubusercontent.com/hoobiboobi/ci-accelerator/v0.6.0/ci/gitlab/build.yml
integrity: sha256-...
inputs:
job-name: build-api
runner-tags: [ci-accelerator]
context: services/api
images: |
$CI_REGISTRY_IMAGE/api:$CI_COMMIT_SHORT_SHA
$CI_REGISTRY_IMAGE/api:latest
- remote: https://raw.githubusercontent.com/hoobiboobi/ci-accelerator/v0.6.0/ci/gitlab/build.yml
integrity: sha256-...
inputs:
job-name: build-web
runner-tags: [ci-accelerator]
context: services/web
images: $CI_REGISTRY_IMAGE/web:$CI_COMMIT_SHORT_SHA

Build arguments and a secret (the value of the masked CI/CD variable NPM_TOKEN, for RUN --mount=type=secret,id=npmrc):

inputs:
build-args: |
NODE_VERSION=22
secrets: |
npmrc=NPM_TOKEN

Check that merge requests build, push only on the default branch: change the job by defining the same job name in your .gitlab-ci.yml (GitLab merges the keys):

build-image:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
build-image-check: # a second include with job-name: build-image-check and push: false
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"

Use the digest in a later job:

deploy:
needs: [build-image]
script:
- echo "deploying $IMAGE_REF"

By default (context-source: local) the job does what every GitLab job does: it checks the repository out (GIT_DEPTH deep, all files) and sends the context to the build node. With a repository of gigabytes that is most of the job’s time, on every job.

With context-source: git the job checks nothing out (GIT_STRATEGY: none on this job only; the other jobs of the pipeline are not touched). The build node fetches the job’s commit from GitLab itself, with the job’s token passed as a build secret, into a copy of the repository it keeps: the first build fetches one commit, every later one only what changed since.

include:
- remote: https://raw.githubusercontent.com/hoobiboobi/ci-accelerator/v0.6.0/ci/gitlab/build.yml
integrity: sha256-<from the release notes>
inputs:
runner-tags: [ci-accelerator]
context: services/api
context-source: git

Measured on a copy of the kubernetes repository (1.5 GB of history, a 373 MB tree) at GitLab: the checkout took 19-27 s and 83-87 MB per job and the context upload 283 MB; with git, the first build on a node fetched 45 MB, every next commit next to nothing, and the build node lays the tree out in about 12 s (once per commit and context folder; parallel jobs that build the same folder of a commit share it).

Use it when the build needs only committed files. It is not for every build:

  • Only committed files are in the context. Files an earlier job made (artifacts) or the job’s script wrote are not there.
  • .dockerignore is not applied (BuildKit ignores it for a git context). Copy the paths the image needs, or use COPY --exclude.
  • The Dockerfile is read from the commit and must be inside the context (dockerfile relative to the repository root, as always).
  • Git LFS files arrive as pointers, and a private submodule fails the build (BuildKit: moby/buildkit#7000, #6046). Keep local for those.
  • A commit a build node holds can be read by its SHA. BuildKit keeps checkouts by commit, and a later build that names a commit already there gets its files without fetching, so without a token. Any job that can build on the farm can read that project’s files, and it need not guess the SHA: a daemon lists its recent builds, git addresses included, to every client. One installation is one trust domain already (builds share the cache); give projects that must not read each other separate build nodes.
  • The build nodes fetch from $CI_PROJECT_URL. They must reach it (and trust its CA if GitLab has its own), not only the job; with GitLab inside buildkit.networkPolicy.egress.clusterCIDRs, add an egress rule for it (buildkit.networkPolicy.egress.extraRules); a runner’s clone_url is not used.
  • The job runs without a checkout. A default: before_script of the pipeline that runs a repository script fails in it: give the job before_script: [], or keep local.
  • GIT_STRATEGY: none comes from a template the job extends (.cia-checkout-git). A GIT_STRATEGY set as a CI/CD variable in the project’s or group’s settings outranks it (the job then checks out again, which works, only slower), and so does an extends: of your own on the same job. With local the job sets no GIT_STRATEGY: the pipeline’s or the project’s applies, as without the component.

The inputs are declared and described in the spec of build.yml, which GitLab validates: an unknown input or a value outside options stops the pipeline before it starts.

Input Default What
job-name build-image Name of the job; one per image
stage build Stage of the job
runner-tags [] Tags that send the job to a ci-accelerator runner
context . Build context directory
context-source local local: the job checks out and sends the context. git: the job checks nothing out, the build node fetches the commit into a copy it keeps (see Huge repositories)
dockerfile <context>/Dockerfile Path of the Dockerfile
target (last stage) Dockerfile stage to build
platform (the node’s) Platforms, comma-separated
build-args KEY=VALUE per line; never secrets
secrets id=VARIABLE per line, from CI/CD variables (File-type: the file’s content)
images $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA References to push, one per line
push true false only builds
registry-auth job-token job-token (GitLab’s registry and Dependency Proxy), docker-auth-config or none
labels true OCI labels source and revision
provenance false Attach a SLSA provenance attestation
interruptible false Let GitLab cancel the job for a newer pipeline; off while moby/buildkit#7268 (a cancelled build can fail another build that shares its steps) is open
timeout-minutes 60 Stop the build after this
buildctl-args More buildctl build arguments, one per line
buildkit-image moby/buildkit:v0.34.2 by digest Image with buildctl for the job; keep it at the daemons’ BuildKit release

Values may use CI/CD variables ($CI_COMMIT_REF_SLUG); write $$ for a literal $.

  • The cache is per daemon. Through the build router a project’s builds go to the node where it built before, so only its first build (with zones on, its first in each zone) is cold; when that node’s daemon is not ready, the build goes to another one. Without the router a project’s first build on each build node is cold.
  • Secrets reach RUN steps through BuildKit’s secret mounts; build arguments do not, and they end up in the image history and in traces.
  • Only Dockerfile builds (dockerfile.v0); other frontends through buildctl-args.
  • ci/gitlab/test/run.sh (make component-test) runs the job’s script in its own image against a fake buildctl, one case per input and failure.
  • ci/gitlab/test/gitlab.sh (make component-gitlab-test) boots GitLab CE in Docker, at 17.9 (the oldest this component supports) and at the runner’s minor, and has GitLab itself read pipelines that include the component: CI lint and pipeline simulation with every kind of input, the job GitLab builds from it (stage, tags, image, variables, an untouched script), and the inputs and integrity hashes it must refuse. Every pull request that changes ci/gitlab/ runs it, and a release whose component changed runs it on the file at its tag on GitHub before anything is published.
  • The end-to-end scenario component (SCENARIOS=component make e2e) runs real pipelines in that GitLab on the box’s runner: checkout, build through the router, push to GitLab’s registry with the job token, the digest in a later job, the cache on the second pipeline, a failing build, and the console’s pages for those jobs.