← Back to articles

Docker · Build Cache

Docker BuildKit Cache Mounts: Reuse pip Downloads When Layers Rebuild

Distinguish layer reuse from a persistent package cache, and keep dependency installation correct when the cache is empty.

A blue build chamber reuses package cubes from an emerald cache vault through a cyan loop.
A package cache can help an installation step even when its layer must rebuild.

A changed requirements file makes Docker rerun dependency installation. A package cache can still save reusable downloads even when the installation layer cannot be reused.

Two caches, two jobs

Layer caching reuses an unchanged build step. A BuildKit cache mount instead gives a running step a persistent directory. Docker documents this Python example:

RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt

Use it in a BuildKit Dockerfile after copying requirements.txt. This path assumes pip runs as root with its default cache location; adjust the target for another user or configuration. Do not combine this example with an option that disables pip caching.

Keep installation in the image

Mount the package cache directory, not the application installation directory. The cache helps pip obtain packages; the installation output must still be available in the resulting image. A cache is an optimization, so the build should also succeed when it starts empty.

Check the builder boundary

A cache on one builder is not automatically available on another. Short-lived CI builders need a deliberate caching design; do not assume a warm local cache will appear in CI.

Validate with two builds

Build once, change a dependency declaration, then inspect the next build log. Confirm installation reruns and check which downloads are reused. Keep dependency version review separate from cache reuse.