Images, Layers & Multi-Stage Builds
Docker & Kubernetes for Interviews: lesson 2 of 12
Order the Dockerfile by how often each line changes, and ship only the output.
Lesson 2 of 12 · 7 min
Images, Layers & Multi-Stage Builds
Step 1 of 11
Each Dockerfile instruction adds a layer: an immutable set of file changes, stacked in order.
The Idea
An image is a read-only template built from a Dockerfile, and each instruction adds a layer: an immutable set of file changes. Docker caches layers, but when one changes, it and every layer after it rebuild. So put what rarely changes — the base, the dependency install — first, and your source last.
Real-World Example
A Node API copies package.json and the lockfile, runs npm ci, then copies the source. A code-only edit reuses the cached dependency layer. A second FROM starts a slim runtime stage that copies in only the built output, leaving the toolchain behind.
The Tradeoff
Copy the whole repository before installing and every edit reinstalls every dependency. Name stages with AS so reordering the file does not break COPY --from. Pin the base image by digest when rebuilds must be identical.
Hands-On
# illustrative — cache-friendly order, two stages
FROM node:22 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:22-slim
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]
Your turn
Put the steps in the right order.
- COPY . . (the source code)
- FROM node:22 AS build
- RUN npm ci
- COPY package.json package-lock.json ./
Mini quiz
1 / 3
You edit one source file. With this lesson's Dockerfile, which steps rebuild?
Sources
- Docker build cache — Docker Docs
- Optimize cache usage in builds — Docker Docs
- Multi-stage builds — Docker Docs
- Building best practices — Docker Docs