The DevOps Drop

Speed Up Docker Builds with BuildKit Cache Mounts for pip, npm and apt

Learn how BuildKit cache mounts keep pip, npm and apt download caches between Docker builds, how they differ from layer caching, the apt and CI pitfalls, and how to measure the speed-up.

Published · 10 min read

Stacked shipping containers at a busy container port
Photo by Ali Mkumbwa on Unsplash

Every time a dependency file changes, Docker's layer cache throws away the whole RUN pip install or RUN npm ci step and downloads every package again. On a project with a few hundred dependencies that is minutes of wasted build time, repeated on every developer laptop and every CI run. BuildKit cache mounts fix this by giving package managers a persistent cache directory that survives between builds without ending up in your image.

This guide is for anyone writing Dockerfiles for Python, Node.js or Debian/Ubuntu based images. You will learn how cache mounts differ from layer caching, how to set them up for pip, npm and apt, what happens to them in CI, and how to check they are actually helping.

Layer caching vs cache mounts

Docker's normal build cache works at the level of whole instructions. If the inputs to a step are unchanged (the instruction text and any files copied into earlier layers), BuildKit reuses the resulting layer. If anything changes, that step and every step after it runs again from scratch.

That is why the standard advice is to copy your lock file before the rest of your source:

COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

This works well when requirements.txt is unchanged. But add one package and the cache key for the RUN step changes, so pip starts with an empty cache and downloads everything again, including the 99% of packages that did not change.

A cache mount solves a different problem. It attaches a directory to a single RUN step that persists across builds on the same builder. The step still re-runs when its inputs change, but the package manager finds its download cache already populated and only fetches what is new. Key properties:

  • The contents of the mount are not written into the image layer, so they add nothing to the image size.

  • The cache lives in the BuildKit builder's storage, not in the image or the registry.

  • It is a cache, not a guarantee. BuildKit can garbage-collect it, and your build must still work when it is empty.

Layer caching and cache mounts complement each other: the layer cache skips unchanged steps entirely, and the cache mount makes the steps that do re-run much cheaper.

Prerequisites

Cache mounts need BuildKit, which is the default builder in current Docker Engine and Docker Desktop releases (and what docker buildx build always uses). Put the syntax directive on the first line of your Dockerfile so you get a current Dockerfile frontend regardless of the Docker version installed:

# syntax=docker/dockerfile:1

The mount is declared with the --mount flag on a RUN instruction. The options you will use most are:

OptionPurpose
targetPath inside the build container where the cache is mounted (required).
idName for the cache. Defaults to the target path. Mounts with the same id share data.
sharingshared (default), private or locked. Controls concurrent access from parallel builds.
uid, gid, modeOwnership and permissions of the cache directory, useful when the step runs as a non-root user.

The full list is in the official Dockerfile reference for RUN --mount=type=cache.

pip

pip caches downloaded and built wheels in ~/.cache/pip, which is /root/.cache/pip when the step runs as root:

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

The most common mistake is leaving --no-cache-dir on the install command, or setting PIP_NO_CACHE_DIR in the environment. Those were the right call before cache mounts, because they kept the cache out of the image. With a cache mount they simply disable the cache you just created. Remove them: the mount already keeps the cache out of the image.

If the step runs as a non-root user, the cache path changes to that user's home directory, and the mount needs matching ownership so pip can write to it:

USER 1000
RUN --mount=type=cache,target=/home/app/.cache/pip,uid=1000,gid=1000 \
    pip install --user -r requirements.txt

Adjust the path to wherever $HOME points for that user in your image.

npm

npm keeps its package cache in ~/.npm. Mount that, keep npm ci so installs stay reproducible from the lock file, and you get offline-speed installs for anything already in the cache:

# syntax=docker/dockerfile:1
FROM node:22-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    npm ci
COPY . .

Do not mount node_modules itself as a cache. Anything in a cache mount is absent from the final image, so your application would start without its dependencies. Cache the download cache, not the install output. The same rule applies to Python virtual environments.

Other package managers follow the same pattern with their own cache directory. Check the tool's documentation for the exact path rather than guessing; a mount on the wrong path builds without error and does nothing.

apt

apt is where most people get tripped up, for two reasons.

The official Debian and Ubuntu images delete the cache for you

The debian and ubuntu base images (and images built on them, such as python:*-slim and node:*-slim) ship a config file, /etc/apt/apt.conf.d/docker-clean, that removes downloaded .deb files after every install. That is sensible without cache mounts, but it empties your cache on every run. Remove it and tell apt to keep downloaded packages, as shown in the Docker documentation:

# 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 \
      build-essential \
      curl

/var/cache/apt holds the downloaded packages and /var/lib/apt holds the package lists fetched by apt-get update. Because both are mounts, neither ends up in the image, so the usual rm -rf /var/lib/apt/lists/* clean-up line is no longer needed.

Use sharing=locked

apt takes a lock on these directories, and it does not cope well with another apt process modifying the same files underneath it. With the default sharing=shared, two builds running in parallel on the same builder (for example a multi-platform build, or two stages that both install packages) can hit lock errors or corrupt the lists. sharing=locked makes the second build wait until the first has released the mount. For pip and npm the default shared mode is generally fine because those caches are designed for concurrent access.

Cache mounts in CI

This is the part that catches teams out. A cache mount lives in the local storage of the BuildKit instance that ran the build. Exporting the build cache with --cache-to exports layers, not cache mount contents. So:

  • On a persistent CI runner (a self-hosted agent, or a long-lived remote builder), cache mounts work exactly as they do locally and give the full benefit.

  • On ephemeral runners, such as GitHub-hosted runners, each job starts with a fresh builder and an empty cache mount. The mount is harmless but does little.

For ephemeral runners the bigger win is exporting and importing the layer cache so unchanged steps are skipped entirely. You need a builder using the docker-container driver, because the default docker driver has limited cache export support:

docker buildx create --name ci-builder --driver docker-container --use

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 registry.example.com/myapp:latest \
  --push .

mode=max exports layers for all stages, including intermediate ones in multi-stage builds, rather than just the final image's layers. That costs more registry storage but gives far better hit rates for multi-stage Dockerfiles.

On GitHub Actions, the gha backend stores the layer cache in the Actions cache service instead of a registry:

name: build
on: push

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/build-push-action@v6
        with:
          context: .
          push: false
          tags: myapp:ci
          cache-from: type=gha
          cache-to: type=gha,mode=max

The two techniques combine well: keep the cache mounts in the Dockerfile so local and persistent builds are fast, and use layer cache export so ephemeral CI skips the dependency step completely whenever the lock file has not changed. See the Docker documentation on cache storage backends for the other options, including S3 and Azure Blob storage.

Measuring the difference

Do not assume the cache is working; check it. Use plain progress output so you get per-step timings:

docker buildx build --progress=plain -t myapp:test . 2>&1 | tee build.log

To get a fair comparison, build once to warm the cache, then add a single new dependency to your lock file and build again. The layer cache is now invalidated for the install step, so the timing reflects what the cache mount saves. Look for the DONE line of the install step in each log. Repeat the same experiment with the mount removed for a before and after figure.

You can also confirm the cache mounts exist and see how much space they use. Cache mount records show exec.cachemount as their type in the verbose output:

docker buildx du --verbose | grep -B3 -A3 exec.cachemount

If the install step is still slow after warming the cache, the usual suspects are:

  • --no-cache-dir or PIP_NO_CACHE_DIR still present.

  • The mount target does not match where the tool actually caches, often because the step runs as a different user.

  • The docker-clean apt config was not removed.

  • You are on an ephemeral CI runner, where the mount always starts empty.

Clearing and maintaining the cache

Because the cache persists, a broken or poisoned package download can persist too. To clear only cache mounts and leave the layer cache alone:

docker buildx prune --filter type=exec.cachemount -f

To force a single Dockerfile to start with a fresh cache without pruning anything, change the mount's id (for example id=pip-v2). A new id means a new, empty cache, which is also a handy way to give different projects sharing one builder their own caches.

On long-lived CI builders, keep an eye on disk usage. BuildKit garbage-collects old cache automatically according to its configured limits, but if a shared builder runs short of space, docker buildx prune with --max-used-space or --reserved-space lets you trim it to a target size.

Summary

Cache mounts are a small Dockerfile change with a large payoff whenever dependency files change:

  • Add # syntax=docker/dockerfile:1 and a --mount=type=cache on each package install step, pointed at the tool's cache directory.

  • Remove --no-cache-dir style flags, and remove docker-clean for apt.

  • Use sharing=locked for apt.

  • Cache the download cache, never node_modules or a virtualenv.

  • In ephemeral CI, pair cache mounts with --cache-to/--cache-from layer cache export, because cache mount contents are not exported.

Once your installs are fast, the next steps are usually multi-stage builds to keep compilers and build tools out of the runtime image, and ordering your COPY instructions so the layer cache is invalidated as rarely as possible.

Related Articles

Continue exploring similar topics and guides.

Lights simulating data flow

DNS Records Explained: A, AAAA, CNAME, MX, TXT and More

DNS records are the building blocks that tell the internet how to route traffic, deliver email, and verify services. Learn how A, AAAA, CNAME, MX, TXT, NS, and other DNS records work with practical examples.

Read article
15 Jul 2026 5 min read
A globe with markers

How DNS Actually Works

A practical introduction to DNS, explaining how domain lookups work, how DNS servers communicate, and why understanding DNS is essential for DevOps and infrastructure work.

Read article
12 Jul 2026 4 min read
Client - Server Diagram with 301 / 302 / 307 HTTP Status Codes

HTTP 301 vs 302 vs 307: What's the Difference?

Understand the differences between HTTP 301, 302 and 307 redirects. Learn when to use permanent and temporary redirects, how they affect HTTP request methods, and how to configure and test redirects using Nginx and curl.

Read article
02 Dec 2026 9 min read