Sub topic 14
BuildKit Cache Mounts for Package Managers
This chapter assumes you can read and write a Dockerfile, know that a cache miss on one step rebuilds every later step, and have used docker build. It covers one BuildKit feature that fixes a limit of layer caching: the package download cache that is lost whenever a dependency step is rebuilt.
The problem layer caching leaves open
The previous chapters showed how to order instructions so that RUN pip install -r requirements.txt stays cached until requirements.txt changes. That works until the file does change. Adding one package to requirements.txt is a cache miss for the install step. The step then runs from scratch, and pip downloads every package again, including the hundreds that did not change.
Layer caching is all-or-nothing per instruction. It caches the whole result of a step, not the pieces the step used. A package manager has its own cache of downloaded archives. In a normal build that cache lives inside the container's filesystem, so it is either baked into the layer (bloating the image) or deleted in the same step (so it is gone on the next build).
A cache mount separates the two. It attaches a persistent directory to one RUN step. The directory lives in the builder's storage, not in the image, so it survives between builds and never becomes part of a layer.
Syntax
Cache mounts require BuildKit, which is the default builder in current Docker releases. On older setups, set DOCKER_BUILDKIT=1. The Dockerfile should also name the frontend syntax on its first line, so the --mount flag is available regardless of the Docker version.
# syntax=docker/dockerfile:1
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
COPY . .The --mount=type=cache,target=... flag belongs to a single RUN instruction. While that command runs, /root/.cache/pip is backed by persistent builder storage. pip finds the archives it downloaded in earlier builds and skips those downloads. When the command ends, the mount is detached. Nothing in /root/.cache/pip is written to the resulting layer.
Where the cache directory is
The target must be the directory your tool uses for its cache. If you point it at the wrong path, the build still succeeds but nothing is reused, so check the path for each tool.
| Tool | Typical cache path (running as root) | Notes |
|---|---|---|
| pip | `/root/.cache/pip` | Used for wheels and HTTP responses |
| npm | `/root/.npm` | Use with `npm ci` |
| Go modules | `/go/pkg/mod` | Also `/root/.cache/go-build` for compiled packages |
| apt | `/var/cache/apt` and `/var/lib/apt` | Needs extra settings, see below |
| Maven | `/root/.m2` | |
| Cargo | `/usr/local/cargo/registry` | Path depends on the base image |
If the build runs as a non-root user, the home directory changes and so must the path. You can check where a tool stores its cache with a command such as pip cache dir.
Examples for other package managers
For npm, mount the cache and keep using npm ci so the install stays reproducible:
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]For Go, two caches help: the downloaded modules and the compiler's build cache.
# syntax=docker/dockerfile:1
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The second RUN mounts two caches. Even when source code changes and the build step is a cache miss, Go reuses compiled packages from /root/.cache/go-build and recompiles only what changed.
apt needs extra care
Debian's docker-clean configuration deletes downloaded .deb files after each install, and the official images often set Binary::apt::APT::Keep-Downloaded-Packages. To benefit from a cache mount you must disable that behavior first:
# syntax=docker/dockerfile:1
FROM debian:bookworm-slim
RUN rm -f /etc/apt/apt.conf.d/docker-clean \
&& echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
apt-get update \
&& apt-get install -y --no-install-recommends curlHere the earlier advice to delete /var/lib/apt/lists in the same step no longer applies. The lists live in the mount, not in the layer, so there is nothing to clean up in the image.
Useful mount options
A cache mount accepts a few options in addition to target.
id=NAMEsets the cache's identity. By default the identity is thetargetpath. Use explicit IDs to share one cache across several stages or to keep two caches at the same path apart.sharing=shared|private|lockedcontrols concurrent access.shared(the default) lets parallel steps use the cache at the same time.lockedmakes a second step wait.privategives a concurrent step its own empty copy. Uselockedfor tools that are not safe for concurrent use, such as apt.uid,gid, andmodeset ownership and permissions of the mount directory. They matter when the step runs as a non-root user.fromandsourceseed the mount from another stage or an image. This is rarely needed.
Edge cases and failure modes
The cache is local to the builder. It lives in the BuildKit builder's storage on one machine. A fresh CI runner starts with an empty cache mount. Layer cache can be exported with --cache-to, but cache mount contents are not carried by the default export. The next chapter shows how to move build cache between machines; plan on CI runners being slower than a developer laptop unless you persist the builder's state.
The cache can be pruned. Builder garbage collection and docker builder prune remove cache mounts. A build must work with an empty cache, only more slowly. Never write a Dockerfile that depends on files being present in a cache mount.
A cache mount does not stop a layer cache miss. The step still reruns when its inputs change. The mount only makes the rerun cheaper. This is why you should keep copying only the manifest files before the install step, as in earlier chapters.
Stale cache can hide problems. A corrupted or outdated cache entry can cause odd failures that disappear with a clean builder. When debugging, rebuild with --no-cache for the layer cache, and run docker builder prune to clear mounts.
Concurrency. If two builds or two stages use the same cache ID with the default sharing=shared, tools that lock poorly can corrupt it. Use sharing=locked when in doubt.
Reproducibility. Because the cache persists, an install may succeed offline on your machine but fail on a clean runner. Test the build with an empty cache before relying on it.
Checking that the cache is used
Build twice, changing the dependency file between builds, and compare the output of the install step:
docker build -t myapp:dev --progress=plain .
echo "requests" >> requirements.txt
docker build -t myapp:dev --progress=plain .In the second build the step is a layer cache miss and runs again. With a working cache mount, pip reports Using cached ... for the packages it already downloaded. Without it, you see Downloading ... for everything. Running docker history myapp:dev shows that the layer for the install step does not include the pip cache, so the image size stays the same as with a plain install.
When to use cache mounts
Use them when a dependency or compile step is slow and its inputs change often, which is common in local development and in CI with persistent builders. They add little for steps that are already cached by layer, and they do not help a fresh runner with no stored state. They also add a # syntax line and BuildKit as requirements. If you must build with the legacy builder, the --mount flag fails with a parse error.
Exercise
You add RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt to a Dockerfile. After you edit one line in requirements.txt, the install step still runs again instead of showing CACHED. Is the cache mount broken? What does the mount change about that rebuild?
Show answer
The mount is not broken. A changed requirements.txt makes the step a layer cache miss, so it runs again. The mount does not prevent that. It makes the rerun faster, because pip reuses the archives it downloaded earlier from the persistent mount at /root/.cache/pip and downloads only the new or changed packages. The pip cache also stays out of the image layer.
Exercise
A teammate mounts a cache at /root/.cache/pip, but the build runs as the user app with home directory /home/app. The build succeeds, yet every build downloads all packages. What is wrong and how do you fix it?
Show answer
pip's cache for the app user is /home/app/.cache/pip, so the mount at /root/.cache/pip is never used. Change the target to /home/app/.cache/pip, and set uid and gid on the mount (or mode) so that app can write to it. You can confirm the correct path with pip cache dir run as that user.