Cache mounts and build secrets

Intermediate · 1 min

RUN --mount keeps package caches between builds without baking them into layers, and passes tokens and SSH keys to one step without leaking them.

Before thisBuildKit and docker buildxBuild arguments and environment variables

Docker · 4 min · from 13:42

Cache mounts and build secrets

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DockerReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • RUN --mount attaches something to a single RUN step that is never committed to a layer: a cache directory, a bind mount of the context, a tmpfs, a secret or an SSH agent.
  • A cache mount persists a directory, such as pip's or Go's cache, across builds on the same builder, so a dependency change re-downloads only what changed.
  • Cache mount contents are not part of the cache key and are not exported with --cache-to, so a fresh CI runner starts with them empty.
  • A secret mount exposes a value as a file under /run/secrets/<id>, or as an environment variable with env=, for one step only. It never appears in a layer or the image history.
  • Changing a secret's value does not invalidate the cache. Add a build argument that you change alongside it if the step must re-run.
  • RUN --mount=type=ssh forwards your SSH agent so a step can clone private repositories without copying a key into the build.

Two things a layer should never hold

A layer is permanent. Whatever a RUN step leaves on disk is committed, cached and shipped. Two kinds of data keep ending up there by accident.

The first is caches. pip, npm, go and apt all download into a cache directory. Leave it and the image grows by hundreds of megabytes. Delete it and the next build downloads everything again, because a changed requirements.txt invalidates the whole install step.

The second is credentials. A build often needs a token for a private package index or an SSH key for a private repository. COPY puts it in a layer. ARG puts it in the image history. Deleting it later does not help, because the earlier layer still has it.

BuildKit’s answer to both is RUN --mount: things attached to one RUN step for its duration and never committed.

Cache mounts

# syntax=docker/dockerfile:1
FROM python:3.14-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt

The cache mount is a directory owned by the builder. The first build fills it. When requirements.txt changes and the step re-runs, pip finds every unchanged wheel already in /root/.cache/pip and downloads only the new ones. Note there is no --no-cache-dir any more: the cache is meant to be used, and it never reaches the image.

The options, from the Dockerfile reference:

  • target: where it appears. id defaults to the target, so two steps with the same target share a cache.
  • sharing: shared (the default) lets concurrent builds use it together, locked makes them wait, and private gives each its own copy.
  • uid, gid, mode: ownership of a new cache directory, for steps that run as a non-root USER.

Package managers that need exclusive access want locked. The reference’s apt example also removes Debian’s docker-clean hook, which otherwise deletes downloaded packages after every install:

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 gcc

Treat a cache mount as a cache. The reference warns that its contents can be overwritten by another build or garbage-collected at any time, so the build must work when it is empty. It is also not exported with --cache-to, the main limitation for CI, covered in build caches in CI.

Bind and tmpfs mounts

--mount=type=bind mounts files from the context, another stage or an image, read-only by default, for one step:

RUN --mount=type=bind,target=. \
    --mount=type=cache,target=/root/.cache/go-build \
    go build -o /out/notes ./cmd/notes

The Go sources are visible to the compiler but never copied into a layer, and only /out/notes is committed. type=tmpfs gives a step a scratch directory in memory.

Secret mounts

The secret goes in on the command line and comes out in exactly one step:

docker buildx build --secret id=npmrc,src=$HOME/.npmrc .
PIP_INDEX_URL=https://user:pass@pypi.internal/simple \
  docker buildx build --secret id=pip_index,env=PIP_INDEX_URL .
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc,required=true \
    npm ci
RUN --mount=type=secret,id=pip_index,env=PIP_INDEX_URL \
    pip install -r requirements.txt

By default a secret is a file at /run/secrets/<id> with mode 0400. target= puts it somewhere else, and env= (Dockerfile 1.10 and later) exposes it as an environment variable for that step instead. required=true fails the build if the secret was not passed, instead of silently running without it.

To check what the build definition records, I converted a Dockerfile with these mounts to LLB using BuildKit v0.35.1’s Dockerfile frontend as a Go library and printed each RUN step’s mounts. Trimmed:

RUN /bin/sh -c pip install -r requirements.txt
  mount CACHE  dest=/root/.cache/pip sharing=SHARED
  secretenv PIP_INDEX_URL from id=pip_index
RUN /bin/sh -c echo build
  mount SECRET dest=/root/.npmrc id=npmrc mode=400 optional=false

Only the secret’s ID is in the graph. The value is fetched from the client during the build and never written into the definition, the cache key, a layer or the history.

That has one consequence from the cache invalidation page: changing a secret’s value does not re-run the step. If you rotate a token and need a rebuild, change a build argument used in the same step, such as ARG CACHEBUST, alongside it.

SSH mounts

To clone a private repository, forward your SSH agent instead of copying a key:

RUN --mount=type=ssh git clone git@github.com:example/private-lib.git
docker buildx build --ssh default .

The step sees a socket to your agent, so even a passphrase-protected key works and the key never enters the build. For a Git URL used as the build context itself, the secrets page shows passing a token as --secret id=GIT_AUTH_TOKEN.

Choosing between build secrets, runtime secrets and a secrets manager is a security lesson of its own. The mechanics are what this one covers.

About the video

The embed is a 3.5-minute chapter, “Leveraging cache and bind mounts” (13:42 to 17:13), from Docker’s “Dockerfile: From Start to Optimized (DockerCon 2023)”, given by David Karlsson, a technical writer at Docker. It adds cache and bind mounts to a Go service’s Dockerfile and shows the rebuild getting faster. It does not cover secret or SSH mounts, which the lesson and anthonywritescode’s video in deeper do. English was judged from the speaker, the description and the English caption track.

What was run: the mount listing is real output from a Go program calling dockerfile2llb.Dockerfile2LLB in BuildKit v0.35.1 and reading the Exec operations, trimmed to the mount fields. Nothing was built and no secret was passed. The options, defaults and cache rules are from the Dockerfile reference, the build secrets page and the cache invalidation page, checked 2026-11-28.

Where this fits

Your builds are faster and leak nothing. Next, building one image for both Intel and ARM machines: multi-platform builds.

Check yourself

  1. 01You switch RUN pip install -r requirements.txt to use --mount=type=cache,target=/root/.cache/pip. Does the image get bigger or smaller?

    Smaller, or at least not bigger. The cache lives outside the layer, so pip's downloaded wheels are never committed, and repeated builds reuse them from the mount.

  2. 02A teammate passes a private registry token with --build-arg and deletes it in the same RUN. Is it safe?

    No. Build arguments are recorded in the image history and provenance even if the file is removed. Pass it with --secret id=token and read it through RUN --mount=type=secret,id=token.

  3. 03You rotate the token passed as a build secret and rebuild. The step that uses it does not run again. Why?

    Secret values are deliberately left out of the cache key. Change a build argument such as CACHEBUST in the same step, or use --no-cache-filter, to force it.

  4. 04Your CI builds with --cache-to type=registry,mode=max, yet every build re-downloads all Go modules even with a cache mount. Why?

    Cache mounts live in the builder's local storage and are not exported or imported with --cache-to and --cache-from. A fresh runner starts with an empty mount.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark