Cache Mounts for Dependencies
What you'll learn: How to speed up Docker builds by reusing package manager caches across builds with RUN --mount=type=cache.
The Problem: Wasted Download Time
Every time you rebuild a Docker image, instructions like apt-get update, npm install, or pip install typically re-download packages—even if you've downloaded them before. This wastes time and bandwidth, especially in CI/CD pipelines running dozens of builds daily.
How Cache Mounts Help
A cache mount is a persistent directory that survives across builds. When you use RUN --mount=type=cache, Docker sets aside a shared folder on the build host where package managers can store their downloaded files. On subsequent builds, the package manager finds those cached files and skips re-downloading.
Think of it like this: Instead of throwing away your grocery bags after shopping (normal builds), you keep a pantry (cache mount) where ingredients stay between cooking sessions.
Basic Syntax
RUN --mount=type=cache,target=/var/cache/apt \
apt-get update && apt-get install -y python3
Here, /var/cache/apt becomes a persistent cache directory. Debian's apt stores downloaded .deb files there, reusing them across builds.
Common Use Cases
- Node.js:
--mount=type=cache,target=/root/.npm - Python:
--mount=type=cache,target=/root/.cache/pip - Go:
--mount=type=cache,target=/go/pkg/mod
Cache mounts complement layer caching (which you learned earlier) but work differently: layer caching checks if instructions changed; cache mounts persist data inside specific directories.
Key Takeaway: RUN --mount=type=cache creates persistent directories that package managers reuse across builds, dramatically reducing download time without changing your final image size.