Sub topic 14
BuildKit cache and secret mounts
This chapter assumes you can write a Dockerfile with FROM, COPY, and RUN, and that you know how layer caching works. It also assumes you have a recent Docker Engine, where BuildKit is the default builder. BuildKit is the build engine behind docker build. It adds RUN --mount, a way to give one RUN instruction temporary access to a cache directory or a secret without storing either in the image.
Two problems layer caching cannot solve
Layer caching works on whole instructions. If package.json changes, the RUN npm ci layer is invalid and every package downloads again, even if only one dependency changed. The layer cache has no way to keep the package manager's download cache between builds.
The second problem is secrets. A build sometimes needs a credential, such as a token for a private package registry. Every way of passing one through normal instructions leaves it in the image:
COPY .npmrc .stores the file in a layer. Deleting it in a laterRUNdoes not remove it from the earlier layer.ARG NPM_TOKENandENV NPM_TOKENare recorded in the image metadata.docker historyshows them.
Mounts fix both problems. A mount exists only while its RUN instruction executes. Nothing in it is committed to the layer.
Enabling the syntax
Mount flags belong to the Dockerfile frontend, which is versioned separately from Docker Engine. Pin it with a syntax directive on the very first line, before any other instruction or comment:
# syntax=docker/dockerfile:1The 1 tag follows the latest stable 1.x release. With BuildKit enabled, Docker pulls that frontend when the build starts. If a build fails with an unknown flag error for --mount, check that BuildKit is active and that the directive is on line one.
Cache mounts
A cache mount is a directory that persists on the build host between builds. Mount it where the tool keeps its download cache:
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]If package.json changes, the layer is rebuilt. But npm finds the packages it downloaded earlier in /root/.npm and only fetches the new ones. The layer cache and the cache mount work together. The layer cache skips the whole step when nothing changed. The cache mount makes the step cheaper when it has to run.
The cache directory is not part of the image. Your image does not grow by the size of /root/.npm, and the next RUN instruction does not see its contents.
Common cache targets
| Tool | Cache directory to mount |
|---|---|
| npm | `/root/.npm` |
| pip | `/root/.cache/pip` |
| Go modules | `/go/pkg/mod` |
| Go build cache | `/root/.cache/go-build` |
| apt | `/var/cache/apt` and `/var/lib/apt` |
The paths assume the build runs as root. If you switch to another user before the RUN, the tool looks in that user's home directory, and you must mount there instead. You can also set uid and gid on the mount.
Cache mounts in a multi-stage Go build
Here is the Go build from the multi-stage chapter with cache mounts added:
# 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 .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The second RUN repeats the /go/pkg/mod mount. Without a cache mount, go mod download would write modules into the layer. With one, the modules exist only in the mounted cache, so every later step that needs them must mount the same cache. The compiled Go build cache in /root/.cache/go-build also persists, so unchanged packages are not recompiled when one source file changes.
The compiled binary goes to /out/app, which is outside any mount. That is why COPY --from=build can find it.
Cache mount options
| Option | Meaning |
|---|---|
| `target` | Path inside the build container. Required. |
| `id` | Name of the cache. It defaults to the target path. Use distinct ids when two targets would otherwise collide, or the same id to share a cache across paths. |
| `sharing` | What happens when two builds use the cache at once: `shared` (default, concurrent access), `private` (each gets its own copy), or `locked` (the second build waits). |
| `mode`, `uid`, `gid` | Permissions and owner of the cache directory. |
| `from`, `source` | Seed the cache from another stage or image path. |
| `ro` | Mount read-only. |
Use sharing=locked for package managers that are not safe for concurrent writes. apt is the usual example.
The apt case
Debian-based images ship an apt setting that deletes downloaded packages after each install, so the cache would always be empty. Disable that setting 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 curlWhere the cache lives
The cache is stored by the builder on the machine that runs the build. Your laptop and a CI runner do not share it. Ephemeral CI runners start with an empty cache every time unless you export and import it with your CI system's cache feature or with docker buildx build --cache-to and --cache-from. Those options handle layer cache. Check your CI documentation for how it persists cache mount directories, since support differs between systems.
Secret mounts
A secret mount makes a file available at /run/secrets/<id> for the duration of one RUN. You supply the content on the docker build command line.
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
--mount=type=secret,id=npmrc,target=/root/.npmrc \
npm ci --omit=dev
COPY . .
USER node
CMD ["node", "server.js"]Here target overrides the default path, so npm sees the credentials file where it expects it. Build with:
docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:1.0 .The id in the Dockerfile and in the --secret flag must match. The file is mounted in memory-backed storage, not written into a layer.
You can confirm that nothing leaked:
docker run --rm myapp:1.0 ls -la /root/.npmrc
docker history --no-trunc myapp:1.0The first command should report that the file does not exist. The second shows the build instructions, and they contain only the --mount flag, not the secret value.
Recent Docker and BuildKit versions can also pass a secret from an environment variable, using --secret id=TOKEN,env=TOKEN on the command line and env=TOKEN in the mount. Check your installed versions before relying on it.
Secret mount options
| Option | Meaning |
|---|---|
| `id` | Name that links the mount to the `--secret` flag. |
| `target` | Path in the container. Defaults to `/run/secrets/<id>`. |
| `required` | If `true`, the build fails when the secret is not supplied. By default a missing secret is silently absent. |
| `mode`, `uid`, `gid` | Permissions and owner of the mounted file. |
Mistakes that still leak secrets
A secret mount protects only what is in the mounted file. These patterns defeat it:
- Copying the secret into the image.
RUN cp /run/secrets/npmrc /app/.npmrcwrites it into a layer. - Printing it. A
RUNthat echoes the value puts it in the build log, which CI systems often keep. - Baking it into output. Some tools write credentials into lock files or config. Check what your install step writes.
- Using it in the final stage by accident. In a multi-stage build, mount secrets only in the build stage. The runtime stage should not need them.
When to use which feature
| Need | Use |
|---|---|
| Speed up package installs when dependencies change | Cache mount on the package manager's cache directory |
| Skip a step when its inputs did not change | Normal layer ordering and `.dockerignore` |
| Pass a credential to one build step | Secret mount |
| Pass a non-secret setting, such as a version number | `ARG` |
| Keep build tools out of the final image | Multi-stage build |
The features combine. A good production Dockerfile often has all of them: a multi-stage layout, cache mounts in the build stage, a secret mount for private registries, and a non-root user in the final stage.
Exercise
A Dockerfile has COPY .npmrc /root/.npmrc, then RUN npm ci, then RUN rm /root/.npmrc. A teammate says the token is safe because the file is deleted. Is that right? Rewrite the install step so the token never enters an image layer.
Show answer
It is not safe. The COPY layer still contains .npmrc, and anyone with the image can extract that layer. The rm only hides the file in later layers. Use a secret mount instead: RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci, add # syntax=docker/dockerfile:1 as the first line, and build with docker build --secret id=npmrc,src=$HOME/.npmrc -t myapp:1.0 ..
Exercise
You add RUN --mount=type=cache,target=/go/pkg/mod go mod download and later a plain RUN go build ./... with no mounts. The build fails because modules are missing. Why, and what are two ways to fix it?
Show answer
The downloaded modules live only in the cache mount, which is not committed to the layer. The plain RUN has no access to it, so Go must download the modules again, and that fails if the build has no network access. Fix it by adding the same --mount=type=cache,target=/go/pkg/mod to the build step, or by dropping the mount on the download step so the modules are stored in the layer.