In this lesson, you will learn how to use BuildKit cache mounts to drastically speed up your image builds by persisting dependency downloads across different runs.
The Problem: Redundant Downloads
Usually, when you run a command like npm install or pip install in a RUN instruction, Docker executes it from scratch if the previous layers changed. Even if you haven't changed your package.json, a change elsewhere in your Dockerfile often forces a re-download of every library. This is slow and wastes bandwidth.
The Solution: BuildKit Cache Mounts
BuildKit, the modern engine behind docker build, allows you to mount a persistent directory during a RUN instruction. This directory acts as a "cache" for your package manager. Because the files are stored on the host machine and injected into the build container, they persist even after the build finishes.
Here is how you implement it for a Node.js project:
# syntax=docker/dockerfile:1
FROM node:18
WORKDIR /app
COPY package.json .
RUN --mount=type=cache,target=/root/.npm \
npm install
COPY . .
How it works:
--mount=type=cache: This tells BuildKit to create a special cache directory.target=/root/.npm: This tells Docker to map that persistent cache directory to the specific folder where npm stores its downloaded packages inside the container.- Persistence: When the build finishes, the files inside
/root/.npmare saved. On your next build, Docker automatically re-attaches that same cache. If your dependencies haven't changed, npm sees the files are already there and skips the network download entirely.
This technique is especially powerful in CI/CD pipelines, where clean environments would normally force you to download your entire node_modules or pip packages on every single code push. By using cache mounts, you transform a multi-minute dependency installation into a few-second operation.
Key Takeaway: Use --mount=type=cache in your RUN instructions to persist package manager download directories, ensuring that dependencies are only downloaded when they actually change.