Sub topic 15
Exporting and Importing Build Cache in CI
This chapter assumes you know how the local build cache decides on a hit or a miss, why a miss invalidates every later step, and how to write a Dockerfile with cache-friendly ordering. It also assumes basic Docker usage and a CI system such as GitHub Actions or GitLab CI.
Why CI loses the cache
On your laptop, the builder keeps cached layers in local storage. The next docker build finds them and reports cache hits. A CI runner is different. Most hosted runners start from a clean virtual machine for every job. The local cache is empty, so every step runs from scratch, even when the Dockerfile and the sources have not changed.
You can fix this by moving the cache somewhere that outlives the runner. The builder can export cache to an external location at the end of a build. It can import cache from that location at the start of the next build. Imported cache entries take part in the same hit-or-miss decision as local ones. A step is a hit only if the instruction and its inputs match an entry, so everything you learned about invalidation still applies.
Local layers versus exported cache
The classic builder cached only whole image layers. BuildKit, the current builder, tracks cache at the level of build graph steps. This means an exported cache can hold more than the layers of the final image. In particular, it can hold intermediate stages of a multi-stage build.
That difference matters for the mode option you will see below. It also explains why pulling the previous image with --cache-from is a weaker approach than exporting a dedicated cache.
Cache backends
The docker buildx build command takes --cache-to and --cache-from options. Each option names a backend with a type= key. The main backends are:
| Backend | Where the cache lives | Typical use |
|---|---|---|
| `inline` | Embedded in the image you push | Simplest setup, small caches |
| `registry` | A separate image reference in a registry | Most CI systems |
| `local` | A directory on disk | Runners that persist a directory between jobs |
| `gha` | The GitHub Actions cache service | GitHub-hosted runners |
| `s3`, `azblob` | Object storage | Teams that already use cloud storage |
The inline backend is limited. It stores cache metadata inside the pushed image, and it can only describe the layers of the final stage. It cannot be used to carry cache for intermediate stages. The other backends are separate from the image and can store all stages.
Exporting to a registry
The registry backend writes the cache as its own image reference. Here is the example from this tutorial's plan:
docker buildx build \
--cache-from type=registry,ref=registry.example.com/app:buildcache \
--cache-to type=registry,ref=registry.example.com/app:buildcache,mode=max \
-t registry.example.com/app:latest \
--push .Each part does a specific job:
--cache-fromtells the builder where to look for cache entries before it runs any step.--cache-totells the builder where to write cache entries after the build.ref=...:buildcacheis a tag reserved for cache. Do not reuse your release tags, because the cache image is not a runnable image.mode=maxexports cache for every stage and every step. The default,mode=min, exports only the layers that end up in the final image.--pushpushes the finished image. It is separate from the cache export.
On the first run the import finds nothing, and the builder runs every step. On later runs it finds matching entries and skips the work.
Choosing min or max
With mode=min, intermediate stages are not exported. Consider a multi-stage build where the builder stage installs dependencies and compiles code. The final stage copies only a binary. The builder stage's layers are not part of the final image, so mode=min leaves them out. A fresh runner must then rebuild the whole builder stage every time, which is the expensive part. For multi-stage builds, use mode=max.
The trade-off is size. mode=max can store many more blobs, so the cache reference grows and the upload takes longer.
Importing cache and fresh runners
A cache import does not download all the layers up front. The builder reads the cache metadata first and downloads a blob only when a step is a hit and its output is needed. This keeps imports cheap when most steps are misses.
A hit still requires an exact match. Cache keys are computed from the instruction, the parent step, and the content of any files involved. So these things produce a miss even with a warm external cache:
- A different base image digest, for example after a tag such as
node:20-slimmoves to a new build. - A changed file in a
COPYstep. - A changed
ARGvalue that the step uses. - A different build platform.
If one of these changes early in the Dockerfile, every later step misses, just as in a local build.
Using the local backend
If your CI keeps a directory between jobs, the local backend avoids a registry round trip:
docker buildx build \
--cache-from type=local,src=/tmp/buildx-cache \
--cache-to type=local,dest=/tmp/buildx-cache-new,mode=max \
-t app:ci \
--load .
rm -rf /tmp/buildx-cache
mv /tmp/buildx-cache-new /tmp/buildx-cacheThe example writes to a new directory and then swaps it in. The local backend does not remove old entries, so exporting into the same directory makes it grow without bound. Writing a fresh export each time keeps only entries that this build used.
A GitHub Actions example
On GitHub-hosted runners, the gha backend uses the cache service that Actions already provides. It needs a builder that supports it, which the docker/setup-buildx-action step sets up.
name: build
on: [push]
jobs:
image:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v6
with:
context: .
push: false
tags: app:ci
cache-from: type=gha
cache-to: type=gha,mode=maxThe gha backend is subject to the cache storage limits of your GitHub plan. When the limit is reached, old entries are evicted, and builds start to miss again.
Combining with cache mounts
Exported cache covers layers. It does not cover the contents of a RUN --mount=type=cache directory. A cache mount lives in the builder's local storage and is not part of any layer, so it is not exported. On a fresh CI runner, the mount starts empty.
This has a practical consequence. If a step's layer is a hit from imported cache, the step never runs, and the mount is not needed. If the layer is a miss, the step runs with an empty mount and downloads every package. Layer cache from the registry still saves you when requirements.txt has not changed. It does not help when one dependency changes. Plan for that case, for example by persisting the builder's state or accepting the full download.
Common errors
- No hits on the first CI run. This is expected. The cache must be exported once before it can be imported.
- The cache is always a miss for the builder stage. Check that you used
mode=max. The defaultmode=minleaves out intermediate stages. - Error saying the cache exporter is not supported. The default
dockerdriver cannot export all backends. Create a builder with thedocker-containerdriver, usingdocker buildx create --use. Thedocker/setup-buildx-actionstep does this for you. - Parallel jobs overwrite each other's cache. Two jobs that write to the same
refrace, and the last writer wins. Give each branch or job its own ref, and import from several refs with repeated--cache-fromoptions. - The cache grows without limit. Use a lifecycle rule on the registry or storage bucket to remove old cache, or switch to the swap pattern for the
localbackend. - Slow exports.
mode=maxuploads more. Measure whether the saved build time is larger than the upload time.
Verifying that the cache works
Build twice on a clean runner and compare the output. In the plain progress output, a step served from cache prints CACHED:
docker buildx build \
--progress=plain \
--cache-from type=registry,ref=registry.example.com/app:buildcache \
--cache-to type=registry,ref=registry.example.com/app:buildcache,mode=max \
-t app:ci .If a step that should have been cached reruns, work backward through the Dockerfile. Find the first step that is not CACHED. Its instruction or its input changed, and every later step rebuilt because of it.
Exercise
A multi-stage Dockerfile has a build stage that runs npm ci and npm run build, and a small final stage that copies only the dist directory. Your CI job uses --cache-to type=registry,ref=registry.example.com/app:buildcache with no mode option. Every run on a fresh runner reruns npm ci, even though package-lock.json has not changed. Why, and what is the fix?
Show answer
The default mode is min, which exports only layers that are in the final image. The npm ci layer belongs to the build stage, so it is never exported and cannot be imported later. Add mode=max to --cache-to so the cache includes every stage.
Exercise
Why should you give the cache its own tag, such as :buildcache, instead of reusing :latest?
Show answer
The cache reference holds cache metadata and blobs, not a runnable image. Writing it to :latest would overwrite your release image, and pulling :latest would fail or give users the wrong content.