Docker cookbook · Intermediate

Speed up builds with BuildKit cache mounts

Stop re-downloading packages on every build when only one dependency changed.

Create a free account to save this page, take notes and track your progress. Sign in

Approach

Mount the package manager's cache directory with --mount=type=cache. It persists between builds on the same builder but never ends up in the image.

Solution

# 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
COPY . .
CMD ["python", "main.py"]

Pitfalls

  • Adding --no-cache-dir together with a cache mount (it disables the benefit).
  • Expecting cache mounts to survive on ephemeral CI runners; export caches with --cache-to.

Variations

  • npm: --mount=type=cache,target=/root/.npm; Go: /go/pkg/mod and /root/.cache/go-build; Maven: /root/.m2.
  • In GitHub Actions, combine with cache-from: type=gha and cache-to: type=gha,mode=max.

Further reading: Optimize cache usage in builds

Reference: https://docs.docker.com/build/cache/optimize/

More Docker recipes

Was this page helpful?