Docker cookbook · Intermediate
Speed up builds with BuildKit cache mounts
Stop re-downloading packages on every build when only one dependency changed.
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-dirtogether 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/modand/root/.cache/go-build; Maven:/root/.m2. - In GitHub Actions, combine with
cache-from: type=ghaandcache-to: type=gha,mode=max.
Further reading: Optimize cache usage in builds
Reference: https://docs.docker.com/build/cache/optimize/
More Docker recipes
- Add a healthcheck to an HTTP service
- Build a layered image for a Spring Boot app
- Build a production image for a Node.js service
- Build a production image for a Python web app
- Build, cache and push images in GitHub Actions
- Build one image tag for amd64 and arm64
- Configure nginx from environment variables
- Develop with Compose and live reload