When I first set up our team’s CI/CD pipeline, I dreaded seeing a developer change just a single line in package.json. Immediately, the server would rebuild from scratch, leaving the whole team waiting 5–7 minutes just to re-download 400 MB of dependencies.
After 6 months of enabling Docker BuildKit Cache Mounts in production, our average build time dropped from 6 minutes to around 35 seconds. If you’re running Docker for Node.js, Python, or Java, this is the very first configuration you should adopt.
Quick start: Speed up builds in 5 minutes
From Docker Engine 23.0 onward, BuildKit is enabled by default on Linux. For older versions, you just need to prepend the environment variable DOCKER_BUILDKIT=1 to your build command.
Next, declare the syntax directive at the top of your Dockerfile and attach the --mount=type=cache flag to the RUN instruction that installs dependencies:
# syntax=docker/dockerfile:1
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
# Mount npm's cache directory from BuildKit into the build step
RUN --mount=type=cache,target=/root/.npm \
npm ci --prefer-offline
COPY . .
RUN npm run build
Run the first build so Docker can populate the cache. Then, try adding a small package like dayjs to package.json and rebuild:
DOCKER_BUILDKIT=1 docker build -t my-node-app:latest .
On the second run, npm no longer downloads the entire node_modules tree from the internet. It reads cached packages directly from /root/.npm and only fetches the newly added package. Installation time typically drops from several minutes to under 10 seconds.
How do Cache Mounts differ from Layer Cache?
Many people new to Docker confuse traditional Docker Layer Cache with BuildKit Cache Mounts. These two mechanisms handle data completely differently:
- Traditional Layer Cache: Docker stores the result of the entire
RUN npm cicommand as an immutable layer. Ifpackage-lock.jsonchanges by even 1 byte, this layer is immediately invalidated (cache miss). Docker is forced to rerunnpm cifrom scratch and re-download every package over the network. - BuildKit Cache Mount: The
--mount=type=cache,target=/path/to/cacheflag creates a dedicated cache directory managed by BuildKit on the host machine. During theRUNstep, this directory is temporarily mounted into the container. Once the command finishes, the cache is unmounted and is not baked into the final image.
This separation solves two problems at once. Your output image stays lean because it doesn’t contain temporary package manager files, while subsequent builds can still reuse 90–95% of previously downloaded packages.
Three parameters you need to know
target: The cache directory path inside the container (e.g.,/root/.npmfor npm,/root/.cache/pipfor pip).id: The unique identifier for the cache. If omitted, BuildKit defaults to using thetargetvalue as theid. When a single build server handles multiple projects, set a distinctidto avoid cache collisions.sharing: Controls how concurrent builds access the cache (e.g., two CI jobs running simultaneously). The default isshared, alongsidelocked(queues builds sequentially) orprivate(creates an isolated cache per build).
Standard configurations for npm, pip, Maven, and CI/CD
Each language stores its cache in a different path and requires specific CLI flags. Below are the 3 configurations I run reliably in production.
1. Node.js (npm)
The npm ci --prefer-offline combination forces npm to check the local cache directory before making requests to the registry:
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,id=npm-cache,target=/root/.npm \
npm ci --prefer-offline --no-audit
2. Python (pip)
Many older tutorials recommend adding --no-cache-dir to shrink image size. However, when using a Cache Mount, you must remove the --no-cache-dir flag. Since /root/.cache/pip is no longer included in the final image, your image stays just as lightweight:
# syntax=docker/dockerfile:1
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN --mount=type=cache,id=pip-cache,target=/root/.cache/pip \
pip install -r requirements.txt
3. Java (Maven)
An average Spring Boot project can require downloading 500–800 MB of .jar files on a clean build. You should mount directly to /root/.m2/repository rather than /root/.m2 to avoid masking your settings.xml file (if present):
# syntax=docker/dockerfile:1
FROM maven:3.9-eclipse-temurin-17 AS builder
WORKDIR /app
COPY pom.xml .
# Download dependencies first to leverage layer cache when pom.xml is unchanged
RUN --mount=type=cache,id=m2-cache,target=/root/.m2/repository \
mvn dependency:go-offline -B
COPY src ./src
RUN --mount=type=cache,id=m2-cache,target=/root/.m2/repository \
mvn package -DskipTests -B
4. Important caveats when running on GitHub Actions
Default GitHub Actions runners are wiped clean after every job. Moreover, Buildx‘s cache-to: type=gha only exports the layer cache—it does not automatically persist the contents inside --mount=type=cache.
With GitHub Actions, you have two options. The simpler approach is pairing it with type=gha,mode=max to preserve the layer cache when package-lock.json rarely changes:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: false
cache-from: type=gha
cache-to: type=gha,mode=max
The default GitHub Actions Cache limit is 10 GB per repository. If you still want to persist Cache Mounts on ephemeral runners, you’ll need a specialized action like buildkit-cache-dance or switch to a self-hosted runner with persistent storage.
Four practical lessons from 6 months in Production
Docker’s official documentation is fairly brief, but after running this in production for a few months, you’ll run into very specific gotchas:
- Permission denied errors with non-root users: When you switch to a user like
USER nodebefore aRUNstep, the package installer may fail to write to a cache directory owned by root. Passuidandgidto the mount:--mount=type=cache,target=/home/node/.npm,uid=1000,gid=1000. - Never clear the cache at the end of a RUN step: Avoid appending
npm cache clean --forceorrm -rf /root/.cache/pip. Doing so wipes out the exact data BuildKit just saved for your next build. - Clean up disk space periodically: The
docker system prunecommand does not clear Cache Mounts by default. After 2–3 months, cache directories on a build server can swell to 20–30 GB. It’s best to set up a monthly cron job running the following command:
# Remove cache mounts unused in the last 30 days
docker builder prune --filter type=exec.cachemount --filter "until=720h" -f
- Tip for reading BuildKit JSON logs: Sometimes a pipeline hits a Buildx driver connection error and dumps a wall of hard-to-read raw JSON from the Docker Engine API. When working directly on a server without an IDE handy, I usually paste that JSON snippet into toolcraft.app/en/tools/developer/json-formatter to format it and inspect cache keys quickly.
Adding just one --mount=type=cache flag to your Dockerfile is enough to eliminate most of the daily wait time for dependency downloads. Try rolling it out to a small service on your team first and measure the build time improvement right on your current pipeline.

