Sub topic 9
Layer ordering and the build cache
This chapter assumes you can write a basic Dockerfile and run docker build and docker run. It also assumes you know what the build context is. Here you will learn how Docker decides to reuse work from earlier builds, and how to order instructions so rebuilds take seconds instead of minutes.
How layers and the cache work
Most instructions in a Dockerfile (RUN, COPY, and ADD) produce a layer. A layer is a stored set of filesystem changes. An image is a stack of these layers.
Before running an instruction, Docker checks whether it already has a cached layer built from the same parent layer and the same instruction. If it does, Docker reuses it and prints CACHED. If it doesn't, Docker runs the instruction and creates a new layer.
The rules differ by instruction:
RUNis compared by its command text. Docker does not check whether the command would give a different result today.RUN apt-get updatestays cached even after new packages are published.COPYandADDare compared by the content of the files they copy, including checksums of the files. Changing one byte in a copied file invalidates that layer.ENV,ARG,WORKDIR, andUSERchange metadata and are compared by their text.
The most important rule is this: once one layer is invalidated, every layer after it is rebuilt too. Docker cannot reuse a later layer when its parent changed.
Order from least to most frequently changed
Because of that rule, put instructions that change rarely near the top. Put instructions that change often near the bottom.
For a Node.js app, the dependency list changes rarely and the source code changes constantly. This Dockerfile copies the dependency manifests first.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]When you edit server.js and rebuild, Docker finds package*.json unchanged. The npm ci layer is reused, and only COPY . . and later layers run.
Compare this with the slow ordering, where COPY . . comes first. Any edit to any file invalidates the copy layer, so npm ci reruns on every build and downloads all dependencies again.
Watching the cache
Build twice and compare the output. With BuildKit, which is the default builder in current Docker, cached steps are marked CACHED.
docker build -t myapp:1.0 .
echo "// edit" >> server.js
docker build -t myapp:1.0 .On the second build, the steps through RUN npm ci should show CACHED. If they don't, something earlier in the Dockerfile or in the files you copied has changed.
Common cache problems
- Copying everything too early.
COPY . .before the install step defeats the cache. Copy only the manifest files first. - Noisy files in the context. A changing log file or
.gitdirectory invalidatesCOPY . .. Exclude them with.dockerignore, which a later chapter covers. - Stale package lists.
RUN apt-get updateon its own line gets cached, and a laterapt-get installcan then use outdated lists and fail. Combine them in oneRUN apt-get update && apt-get install -y curl. - Frequently changing values early on. An
ARGthat holds a build timestamp or commit hash invalidates every layer after its first use. Declare it late. - Needing fresh results. To rebuild everything, use
docker build --no-cache .. To refresh only the base image, usedocker build --pull ..
Exercises
Exercise
You edit one line in server.js. Your Dockerfile has COPY . . as the second instruction, followed by RUN npm ci. Which steps rerun, and how do you change the Dockerfile so npm ci stays cached?
Show answer
Both COPY . . and RUN npm ci rerun, because the changed file invalidates the copy layer and every layer after it. Copy only package*.json first, run RUN npm ci, and then run COPY . .. An edit to server.js then invalidates only the final copy and later layers.
Exercise
A RUN apt-get update line is cached from three months ago. Why can this cause a failing install later, and what is the fix?
Show answer
Docker compares RUN by its command text, so it reuses the old layer with outdated package lists. A later apt-get install may ask for package versions that no longer exist. Put apt-get update && apt-get install -y <packages> in a single RUN, so the lists are refreshed whenever the install line changes.