Image Layers and the Build Cache
An image is a stack of layers, one per Dockerfile step. Docker caches each layer, and a rebuild reuses every layer whose step and files did not change.
Build twice
The second build reuses the cache and prints CACHED at the COPY step.
docker build -t g4-greet:1.0 . >/dev/null
docker build -t g4-greet:1.0 . 2>&1 | grep -c CACHEDOrder the steps well
Install first, then copy code, so code edits reuse the install layer.
FROM python:3.12-slim
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .Example
docker build -t g4-greet:1.0 . >/dev/null
docker build -t g4-greet:1.0 . 2>&1 | grep -c CACHEDKey points
- Layer: one step of a Dockerfile, stored as one read-only slice.
- The build cache holds layers from earlier builds for reuse.
- A rebuild reuses a layer when its step and its files are unchanged.
- A changed step busts its own layer and every layer after it.
- Put slow steps early and changing files late, so the cache works hardest.
In this example, the same build runs twice. The first build runs every step. The second build prints CACHED at the COPY step and finishes at once. The cached line proves the layer was reused, not rebuilt.
Note
COPY of a changed file busts the cache at that line, even when the file changed by one byte.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Why do slow install steps go early in a Dockerfile?