Card 06/ 07
Practice: Predicting Which Build Steps the Cache Reuses
Three changes to one Dockerfile; work out what each one costs before you look.
The build cache keeps the result of each Dockerfile instruction as a layer. When a layer's inputs change, that instruction runs again, and so does every instruction below it; everything above is reused. The Dockerfile below is ordered for the cache, and each question makes one change to the project. For each, write down which instructions run again before you open the answer.
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
CMD ["node", "server.js"]You edit a comment in server.js. Which instructions run again?
COPY . . and CMD. The source copy's layer changed, so everything after it runs again, but npm ci is above that copy and keeps its cache. CMD only records the start command, so it costs nothing.
You add a dependency to package.json. Which instructions run again?
COPY package.json package-lock.json ./ onwards, so the install as well. That is correct: the dependencies really did change.
You change FROM node:20-alpine to FROM node:22-alpine. Which instructions run again?
All of them. The first layer changed, so nothing below it has a cached layer to sit on.
← → move through sections and cards