BuildKit Cache Mounts
Why npm ci Still Takes 4 Minutes
Developer toolingdeveloper tooling / containers & CI
The symptom
Your Dockerfile is "correctly ordered" — deps before source:
COPY package*.json ./
RUN npm ci
COPY . .
Layer caching works. Yet every time you touch package.json (a dozen times a week), CI burns 3m40s re-downloading all 1,200 packages from zero.
Reason it through
Layer cache is all-or-nothing. The key is parent layer + command string + digest of what was COPYed. package.json changed → key changed → that RUN re-executes completely.
And when it re-executes, ~/.npm is empty. Your ordering isn't wrong. The gap is conceptual: layer caching caches RESULTS (finished layers). What you actually want cached is the INTERMEDIATE state — the package manager's download cache — which layer caching has no concept of.
The fix
# syntax=docker/dockerfile:1
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci
That mounts a persistent writable scratch dir for the lifetime of that one RUN. It is not part of the resulting layer — so it doesn't bloat the image, and it does not participate in the cache key. npm finds its tarballs locally: 3m40s → ~25s, even on a full cache miss.
Same shape everywhere:
- pip → target=/root/.cache/pip
- Go → /root/.cache/go-build and /go/pkg/mod
- cargo → /usr/local/cargo/registry
- apt → /var/cache/apt (add sharing=locked)
The gotcha that makes people say "cache mounts don't work"
Cache mounts live on the BUILDER's local state. Not in the image. Not in your exported cache.
So locally it's magic. On a fresh ephemeral CI runner the mount is empty every single run — and no, --cache-to type=gha or type=registry does NOT export cache mounts. Only layers. You wire it up, see zero improvement, and blame the feature.
To get it in CI you need a builder that survives between runs:
- a persistent/self-hosted BuildKit (docker buildx create --driver remote)
- a managed builder (Docker Build Cloud, Depot)
- or a runner whose BuildKit state dir is itself cached
Otherwise: use layer cache + registry cache export for CI, and cache mounts to make local rebuilds fast. Both, for different jobs.
One more nuance: sharing
Parallel builds hit the same mount. Defaults:
- sharing=shared (default) — fine for npm/pip, they're multi-process safe
- sharing=locked — serialize; use for apt and anything with a global lockfile
- sharing=private — each build gets its own copy
Getting this wrong on apt gives you beautifully confusing intermittent dpkg lock errors.
Your exercise
- touch package.json, time a build. Note the install duration.
- Add the cache mount. Build once (populates it), touch package.json again, build again. Time the install step now.
- Run: docker buildx du --verbose
Find your cache mount entry and its size. Then answer: if you added that mount to a 3-stage build where two stages run npm ci, how many cache mounts exist — and would you want sharing=locked there?