Skip to content

BuildKit cache mounts — fast, reliable Docker builds

Use BuildKit cache mounts to persist package manager caches across builds. Patterns for apt, pip, npm, Go modules, and Cargo, plus the gotchas that bite in CI.

A clean Docker build of a Node app re-downloads every npm package every time. A clean Python build re-downloads every wheel. A clean Go build re-downloads every module. BuildKit’s cache mounts let you persist those caches across builds at the host level — so even a “no-cache” image build benefits from the same ~/.npm your laptop dev cycle uses. The difference is often the gap between a 30-second iteration and a 4-minute one.

How to verify

Check whether BuildKit is enabled and whether your Dockerfile is using cache mounts:

docker buildx version
docker buildx ls
DOCKER_BUILDKIT=1 docker build --progress=plain -t myapp . 2>&1 | head -30

# Inspect Dockerfile for cache mount syntax
grep -nE "RUN --mount" Dockerfile

# Where does BuildKit keep its cache?
docker buildx du
docker buildx prune --help

If docker buildx version reports an error, the plugin isn’t installed (Compose-era Docker installs ship it; very old hosts may not). If --progress=plain shows every RUN running from scratch each build, you’re not benefiting from cache mounts.

What’s happening

BuildKit is Docker’s modern build subsystem, default since Docker 23. It replaces the legacy builder’s linear layer cache with a directed-acyclic-graph (DAG) representation: stages run in parallel when independent, cache reuse is more aggressive, and a new instruction — RUN --mount — lets you attach ephemeral or persistent mounts to a single RUN step.

The most useful --mount types:

  • type=cache — a writable directory that persists across builds, scoped by id and target. The cache lives on the host (or in a remote builder), not in any image layer.
  • type=bind — a read-only mount of the build context, used by COPY under the hood.
  • type=secret — a temporary mount of a host file that doesn’t end up in any layer. See Docker secrets handling.
  • type=ssh — forward your SSH agent into the build, for cloning private repos.
  • type=tmpfs — RAM-backed scratch directory.

Cache mounts are the high-leverage one. Done right, they cut clean-build times by 5-10x for any language with significant dependency downloads.

The procedure

  1. Enable BuildKit explicitly (it’s the default on modern Docker, but make it explicit for older hosts):
export DOCKER_BUILDKIT=1
# Or use buildx, which is BuildKit-only:
docker buildx build -t myapp .
  1. Add the syntax directive at the top of the Dockerfile — required for --mount:
# syntax=docker/dockerfile:1.7
  1. Cache for apt (Debian/Ubuntu base images):
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
    --mount=type=cache,target=/var/lib/apt,sharing=locked \
    rm -f /etc/apt/apt.conf.d/docker-clean \
 && apt-get update \
 && apt-get install -y --no-install-recommends \
      build-essential libpq-dev

Two important changes from the standard pattern: remove /etc/apt/apt.conf.d/docker-clean (which forces apt to wipe its cache on every install — fighting against the cache mount), and do not rm -rf /var/lib/apt/lists/* at the end (the cache mount handles persistence, and the cache itself doesn’t end up in the layer).

  1. Cache for pip (Python):
RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
    pip install --no-cache-dir -r requirements.txt

Note: pip install --no-cache-dir is correct — it tells pip not to write its own per-build cache, because the mount provides a persistent one. The cache mount is the better cache.

  1. Cache for npm:
RUN --mount=type=cache,target=/root/.npm,sharing=locked \
    npm ci --prefer-offline --no-audit

--prefer-offline tells npm to use cached tarballs when possible, hitting the registry only for missing entries.

  1. Cache for Go modules and the build cache:
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    go build -o /out/app ./cmd/server

Go has two caches: the module cache (/go/pkg/mod) and the build cache (/root/.cache/go-build). Cache both for maximum effect.

  1. Cache for Cargo (Rust):
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/app/target \
    cargo build --release
  1. The sharing mode controls concurrent access. locked (the default for shared mounts) means parallel builds wait on the lock — safe but slower. shared means builds may interleave writes — fast but can corrupt caches that don’t expect concurrent writers. Use private to give each build its own copy. For language package managers, locked is usually right.

  2. The id lets you partition caches across distinct contexts:

RUN --mount=type=cache,target=/root/.npm,id=npm-${PROJECT_NAME} \
    npm ci

Multiple projects on the same builder won’t fight over the same cache directory.

  1. In CI, the host-level cache is per-runner. For CI fleets with ephemeral runners, BuildKit can use a remote cache backend:
docker buildx build \
  --cache-from type=registry,ref=registry.example.com/myapp:buildcache \
  --cache-to   type=registry,ref=registry.example.com/myapp:buildcache,mode=max \
  -t myapp:${SHA} .

The cache layer lives in your registry; every CI runner pulls it before building, then pushes any new layers back.

  1. Prune the cache periodically so it doesn’t grow unbounded:
docker buildx du                          # show cache size
docker buildx prune --keep-storage 10GB   # keep up to 10 GB, evict rest
docker buildx prune --all                 # wipe entirely

A weekly cron docker buildx prune --keep-storage 20GB on each builder is a sensible default.

Common pitfalls

  • Forgetting the # syntax=docker/dockerfile:1.7 directive — --mount is silently treated as part of the command, and your build fails or produces strange results.
  • Mixing sharing=shared with a tool that doesn’t tolerate concurrent writers (e.g. some npm versions corrupt the cache). Stick with locked unless you’ve tested.
  • Cache mount paths must match the tool’s expected cache location for the running user — if your build runs as a non-root user, point the mount at that user’s home cache directory, not /root/.
  • Expecting cache mounts to speed up CI on a fleet of ephemeral runners without a remote cache backend — they only persist on the builder host.
  • Using type=cache for things that need to end up in the image (e.g. target=/app/node_modules). The cache mount disappears at the end of the RUN step; if the runtime stage needs node_modules, install into a regular path and COPY from there.

We turn these cache mounts on for every client build pipeline — they’re the cheapest CI speedup available and remove the most common “the build is so slow” complaint. Combined with the rest of our managed operations build hardening, they bring iteration time back to where it should be.