Card 02/ 07

ExampleDifficulty: Intermediate1 min

Build Cache Example: The Same Build, Run Twice

Nothing changed between the two builds, and the output says so on every line.

Building the same project twice, with no change in between, shows the build cache at work: the second build reuses every layer (the stored result of one Dockerfile instruction) from the first and finishes in a fraction of the time.

The first build runs every instruction. The step numbers count the Dockerfile's instructions, and the time on the right is how long each one took:

bash
docker build -t my-api:1 .
 => [2/5] WORKDIR /app                      0.1s
 => [3/5] COPY package.json package-lock.json ./   0.0s
 => [4/5] RUN npm ci                        9.8s
 => [5/5] COPY . .                          0.1s
 => exporting to image                      1.2s

The second build, with nothing changed:

bash
docker build -t my-api:1 .
 => CACHED [2/5] WORKDIR /app
 => CACHED [3/5] COPY package.json package-lock.json ./
 => CACHED [4/5] RUN npm ci
 => CACHED [5/5] COPY . .
 => exporting to image                      0.3s

Every step says CACHED. The nine seconds of npm ci were not spent again, because the instruction and the layer underneath it were both unchanged. Only exporting the image still ran, and it took a third of a second.

So CACHED on a line means that instruction cost nothing. When a build is slow, the first line without CACHED is where the time starts going.