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
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