Our image builds were fast on a laptop and slow in CI for the most boring reason: every CI job ran on a fresh virtual machine or pod, so the Docker build cache was empty every time. A 40-second incremental build became a seven-minute full build, multiplied by four images and a matrix of two architectures.
BuildKit, the engine behind docker buildx build, can export its cache to somewhere that outlives the runner and import it on the next build. The flags are --cache-to and --cache-from. The hard part is choosing where to put the cache and keeping several images from fighting over it. This guide compares the backends and shows the configuration we settled on for GitHub Actions and GitLab. Layer ordering in the Dockerfile still matters more than any backend; post 33 covers that, and post 146 goes deep on registry cache with mode=max for multi-stage builds.
Why the default cache is empty
The Docker build cache lives inside the BuildKit instance's state directory. On GitHub-hosted runners, the VM is destroyed after the job. On GitLab with the Docker or Kubernetes executor and Docker-in-Docker, the dind service container is destroyed after the job. Either way, the next job gets a new BuildKit with nothing in it. --cache-from with a plain image reference only helps when that image was built with inline cache metadata, and even then only for the final stage.
The backends at a glance
Backend | Where cache lives | Good for | Watch out for |
|---|---|---|---|
| GitHub Actions cache service | GitHub-hosted runners | Shares the repo cache budget; needs scopes for multiple images |
| Separate image ref in a registry | Any CI, multi-stage builds | Push permissions; registry storage cost |
| Inside the pushed image | Simple single-stage images | Only |
| Directory on disk | Self-hosted runners with persistent disks | Grows forever unless you rotate it |
| Object storage bucket | Large caches, multi-cloud runners | Credentials in the build job; lifecycle rules |
All exporters except inline support mode=min (export only layers of the final image) and mode=max (export every intermediate stage). For multi-stage builds, mode=max is the one that makes the builder stage cacheable.
GitHub Actions: type=gha with scopes
The gha backend talks to the same cache service as actions/cache. With docker/build-push-action the runtime token and URL are passed automatically:
jobs:
image:
runs-on: ubuntu-24.04
strategy:
matrix:
service: [api, worker, web]
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
context: services/${{ matrix.service }}
push: ${{ github.ref == 'refs/heads/main' }}
tags: ghcr.io/example-org/${{ matrix.service }}:${{ github.sha }}
cache-from: type=gha,scope=${{ matrix.service }}
cache-to: type=gha,scope=${{ matrix.service }},mode=max
The scope parameter is the important part. Without it, every image writes to the default scope, and each matrix leg replaces the cache index of the previous one. We saw a hit rate of roughly one in three before adding scopes, because only the last image to finish had its cache index on the next run.
Two more behaviours to plan for:
Same branch rules as
actions/cache. Pull requests can read caches from their base branch but not from other pull requests. Build on the default branch after merge so PRs have something warm to read.Same storage budget. Layer blobs count against the repository's cache budget, 10 GB by default, shared with dependency caches.
mode=maxon four large images can push dependency caches out. Check usage withgh cache list --sort size_in_bytes.
If you build with arm64 and amd64 legs, include the platform in the scope (scope=api-arm64), because layers differ per platform.
GitLab: registry cache with a dedicated ref
GitLab has no equivalent of the gha service, and the runner cache (cache: keyword) stores files, not BuildKit layers. The reliable option on ephemeral runners is a registry cache in the project's container registry, under its own tag so it never gets confused with a deployable image.
build-api:
image: docker:28
services:
- docker:28-dind
variables:
DOCKER_TLS_CERTDIR: "/certs"
CACHE_REF: $CI_REGISTRY_IMAGE/api:buildcache
CACHE_TO: type=registry,ref=$CI_REGISTRY_IMAGE/api:buildcache,mode=max,image-manifest=true
before_script:
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
- docker buildx create --use --driver docker-container
script:
- >
docker buildx build services/api
--cache-from type=registry,ref=$CACHE_REF
--cache-to "$CACHE_TO"
--tag $CI_REGISTRY_IMAGE/api:$CI_COMMIT_SHORT_SHA
--push
Notes from running this for a year:
The default
dockerdriver cannot export cache to a registry; create adocker-containerbuilder first, as above.image-manifest=truewrites the cache as a regular OCI image manifest, which some registries handle better than the older cache index format.Merge requests should read the main branch cache but write to their own ref, so a branch with experimental changes does not overwrite the cache everyone uses. We override
CACHE_TOper pipeline type in the job's rules:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
CACHE_TO: type=registry,ref=$CI_REGISTRY_IMAGE/api:buildcache,mode=max,image-manifest=true
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
variables:
CACHE_TO: type=registry,ref=$CI_REGISTRY_IMAGE/api:buildcache-mr$CI_MERGE_REQUEST_IID,mode=max,image-manifest=true
Add a container registry cleanup policy that removes
buildcache-mr*tags after a few days.
Self-hosted runners: type=local or a persistent builder
On self-hosted runners with a persistent disk, the simplest fast option is a long-lived BuildKit instance (a remote builder) that keeps its own cache. Every job connects to it instead of starting a fresh one:
docker buildx create --name shared --driver remote tcp://buildkitd.example.com:1234 --use
If a shared builder is not an option, type=local exports to a directory you persist between jobs. The local exporter does not prune old data, so the usual pattern is to write to a new directory and swap it in after a successful build:
docker buildx build . \
--cache-from type=local,src=/cache/api \
--cache-to type=local,dest=/cache/api-new,mode=max
rm -rf /cache/api && mv /cache/api-new /cache/api
A remote builder needs network protection and authentication (mTLS) because anyone who can reach it can run builds.
Measuring whether it works
Look at the build output, not the total job time. Cached steps print CACHED:
#9 [builder 3/6] RUN npm ci
#9 CACHED
#12 [builder 5/6] RUN npm run build
#12 DONE 41.3s
We track three numbers per image in the job summary: total build time, count of CACHED steps, and size of cache exported. A sudden drop in cached steps usually means a scope collision or an early COPY . . that invalidates everything after it.
Common mistakes
Mistake | Why it hurts | Do this instead |
|---|---|---|
No | Images overwrite each other's cache index | One scope per image and platform |
| Builder stage never cached | Use |
Writing cache from every PR to the main ref | Experimental branches pollute the shared cache | PRs read main, write their own ref |
Default | Export not supported | Create a |
Unbounded local cache directory | Disk fills on self-hosted runners | Write new, swap, or prune on a schedule |
Treating cache as guaranteed | Eviction makes builds randomly slow | Budget for cold builds; alert on trends |
Key takeaways
Ephemeral runners always start cold; cache must be exported and imported explicitly.
On GitHub-hosted runners,
type=ghais the easiest backend, but give every image its own scope and watch the shared budget.On GitLab, use a registry cache under a dedicated tag, with branch-specific refs for merge requests.
mode=maxis needed for multi-stage builds, at the cost of more storage.Measure cached steps, not just job duration.
References
Docker Docs, Cache storage backends: https://docs.docker.com/build/cache/backends/
Docker Docs, GitHub Actions cache backend: https://docs.docker.com/build/cache/backends/gha/
Docker Docs, Registry cache backend: https://docs.docker.com/build/cache/backends/registry/
Docker Docs, Cache management with GitHub Actions: https://docs.docker.com/build/ci/github-actions/cache/
GitLab Docs, Use Docker to build Docker images: https://docs.gitlab.com/ci/docker/using_docker_build/
GitLab Docs, Cleanup policy for container registry: https://docs.gitlab.com/user/packages/container_registry/reduce_container_registry_storage/
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.