Sub topic 12
Faster builds with BuildKit cache mounts
This chapter assumes you can read a multi-stage Dockerfile and know how layer caching and instruction order work. You should also be able to run docker build and docker image ls. Earlier chapters covered how a changed layer invalidates every layer after it. Cache mounts address a gap in that model.
The problem layer caching leaves open
Layer caching is all-or-nothing per instruction. Suppose requirements.txt gains one new package. The COPY requirements.txt . layer changes, so the RUN pip install -r requirements.txt layer is rebuilt from scratch. pip then downloads every package again, including the hundreds you already had.
You could keep pip's download cache inside the image, but that makes the image larger. You could also pass --no-cache-dir, which keeps the image small but throws away the speedup. A BuildKit cache mount avoids this trade-off.
What a cache mount is
A cache mount is a directory that BuildKit, Docker's build engine, keeps on the builder between builds. You attach it to a single RUN instruction. Three properties matter:
- The directory is mounted while the command runs, so tools like pip, npm or the Go compiler can read and write it.
- The directory contents are not part of the resulting layer. They never add to image size.
- The directory persists after the build, so the next build starts with whatever the previous one left there.
The syntax is a flag on RUN:
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txtBuildKit is the default builder in current Docker Engine releases. On older setups, enable it with DOCKER_BUILDKIT=1 or put # syntax=docker/dockerfile:1 on the first line of the Dockerfile. Adding the syntax line is harmless everywhere.
A Python example
This is the Python build from the earlier chapter, now focused on the cache mount:
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
FROM python:3.12-slim
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY . .
USER nobody
CMD ["python", "app.py"]The mount targets /root/.cache/pip, which is where pip stores downloaded wheels and HTTP responses when it runs as root. The virtual environment at /opt/venv is not a cache mount. It lives in a normal layer, so the second stage can copy it with COPY --from=build.
To see the effect, build once, add a package to requirements.txt, and build again with plain progress output:
docker build -t myapp:cm .
echo "requests" >> requirements.txt
docker build --progress=plain -t myapp:cm .The second build still re-runs the pip install step, because the layer cache was invalidated. This time pip finds most packages in its cache and prints Using cached ... instead of downloading them. Only the new package is fetched.
Where the cache directory lives for common tools
The target path must be the directory the tool really uses. A wrong path creates an empty mount that nothing writes to, and the build silently gets no speedup.
| Tool | Cache directory (running as root) | Notes |
|---|---|---|
| pip | `/root/.cache/pip` | Set by `PIP_CACHE_DIR` if you override it |
| npm | `/root/.npm` | Use with `npm ci` |
| Go modules | `/go/pkg/mod` | Default `GOMODCACHE` in the `golang` image |
| Go build cache | `/root/.cache/go-build` | Speeds up repeated compiles |
| apt | `/var/cache/apt` and `/var/lib/apt` | Needs extra setup, shown below |
If you are unsure, run the tool in a container and check its configuration. For example, go env GOMODCACHE GOCACHE prints both Go paths, and pip cache dir prints pip's.
Node.js and Go examples
For Node.js, mount npm's cache during the dependency install in the build stage:
# syntax=docker/dockerfile:1
FROM node:20 AS build
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build
FROM node:20-slim
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "dist/index.js"]Both stages share the same cache directory, so the production install reuses packages the build stage already downloaded. Both stages run as root during RUN, so the path is the same.
For Go, you can cache both the module download directory 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 -ldflags="-s -w" -o /out/app .
FROM scratch
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The compiler output goes to /out/app, which is outside any mount. This matters. If you wrote the binary into a cache directory, it would vanish from the layer and COPY --from=build would find nothing.
Options you will actually use
You can add options to --mount=type=cache after the target, separated by commas.
| Option | Purpose |
|---|---|
| `id=NAME` | Names the cache. By default the id is the target path. Use a shared id to reuse one cache across different targets or stages. |
| `sharing=shared` | Default. Several builds can read and write the cache at the same time. |
| `sharing=locked` | One build at a time uses the cache. Others wait. |
| `sharing=private` | Each concurrent build gets its own copy if the cache is already in use. |
| `uid=`, `gid=`, `mode=` | Set ownership and permissions of the mount directory. |
Use sharing=locked for tools that corrupt their data when two processes write at once. The apt package manager is the standard case. Debian-based images ship an apt configuration that deletes downloaded packages after install, which defeats caching. You have to turn that off 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 curlIf a later stage runs as a non-root user, add uid to match. For example, --mount=type=cache,target=/home/node/.npm,uid=1000 gives the node user (uid 1000 in the official image) write access. Without it, the mount is owned by root and the tool fails with a permission error or silently skips caching.
Limits and failure modes
Keep these in mind when you rely on cache mounts.
- The cache is not part of the image. Nothing in a cache mount is available when you run the container. Do not install packages into a cache mount target and expect to use them later.
- The build must work with an empty cache. The cache can be pruned at any time by
docker builder prune, or by the builder's garbage collection when disk space runs low. A build that only succeeds with a warm cache is broken. - Builds are less reproducible. The same Dockerfile and sources can behave differently depending on what the cache holds. Stale entries can mask problems, such as a package that was removed from the registry.
- The cache is local to the builder. A fresh CI runner starts with an empty cache, so cache mounts often give no benefit there. Registry cache export (
--cache-to) stores layers but does not include cache mount contents. You need extra tooling or a persistent builder to carry them across runs. - Concurrency can bite. The default
sharing=sharedis unsafe for tools that do not tolerate parallel writers. Chooselockedwhen in doubt.
Checking that it helps
Measure instead of assuming. Run a build with a changed dependency file and compare timings with and without the mount. Add --progress=plain to see per-step timing, and compare docker image ls output to confirm the image size did not change. If the sizes differ, the mount target is probably wrong or the command is writing its outputs into the mount.
Exercise
A teammate adds RUN --mount=type=cache,target=/app/node_modules npm ci to a build stage, then runs COPY --from=build /app/node_modules ./node_modules in the final stage. The final image fails at startup because modules are missing. Why, and what is the fix?
Show answer
Files inside a cache mount are not stored in the layer, so /app/node_modules is empty in the build stage's filesystem after the RUN finishes, and the COPY --from=build copies nothing. Mount npm's download cache (/root/.npm) instead, and let npm ci write node_modules into the normal layer filesystem.