Sub topic 9
Layer ordering and the build cache
This chapter explains how Docker decides whether to reuse earlier work during a build, and how to order your instructions so that small code edits do not trigger slow rebuilds. It assumes you can write a basic Dockerfile with FROM, COPY, RUN, and CMD, and that you can run docker build and docker run. Earlier chapters covered the build context, WORKDIR, COPY, and RUN. Here you use them with caching in mind.
How layers work
An image is a stack of read-only layers. Instructions that change the filesystem (RUN, COPY, ADD) each produce a layer that holds the files that instruction added or changed. Instructions such as ENV, CMD, EXPOSE, and USER only change image metadata, so they add no files, but they still take part in caching.
Layers are content-addressed and shared. If two images start with identical layers, Docker stores them once. This is also what makes the build cache possible: if Docker can prove a step would produce the same result as before, it reuses the stored layer instead of running the step again.
The cache rules
Docker walks through the Dockerfile from top to bottom. For each instruction it asks whether a cached layer exists that was built from the same parent layer with the same instruction. The check differs by instruction type:
| Instruction | What Docker compares to decide on a cache hit |
|---|---|
| `RUN` | The command text, as a string. It does not look at what the command would do. |
| `COPY` and `ADD` | The instruction text and a checksum of the contents of every file being copied. File modification times are ignored. |
| `ENV`, `ARG`, `WORKDIR`, `USER`, `CMD`, and others | The instruction text, including its values. |
| `FROM` | The image ID the tag resolves to in the local image store. |
The most important rule is this: once one instruction misses the cache, every instruction after it also runs again. Each layer depends on its parent, so a new parent means every child must be rebuilt. This is why order matters. A change near the top of the file invalidates almost everything. A change near the bottom invalidates very little.
A slow ordering and a fast one
Consider this Dockerfile. It works, but it caches badly.
FROM node:20-slim
WORKDIR /app
COPY . .
RUN npm ci --omit=dev
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]COPY . . copies the whole project before dependencies are installed. Editing any single source file changes the checksum of that COPY layer. The cache misses at that step, so RUN npm ci runs again and downloads every package, even though package.json did not change.
The fix is to copy only the dependency manifests first, install, and then copy the rest.
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"]Now the install layer depends only on package.json and package-lock.json. When you edit server.js, the first COPY and the RUN npm ci are cache hits. Only COPY . . and the steps after it run. A rebuild drops from a minute or more to a second or two.
The general principle is to order instructions from least likely to change to most likely to change:
- Base image and system packages.
- Dependency manifests and the dependency install.
- Application source code.
- Metadata that rarely matters for speed, such as
EXPOSEandCMD.
Cheap metadata instructions can go almost anywhere. Putting an ENV or ARG that changes often near the top is a mistake, because it invalidates everything beneath it.
Watching the cache work
Build the fast version twice and look at the output. With BuildKit, which is the default builder in current Docker releases, cached steps are labeled CACHED.
docker build -t myapp:1.0 .
echo "// touch" >> server.js
docker build -t myapp:1.0 .On the second build, the lines for FROM, WORKDIR, COPY package*.json ./, and RUN npm ci --omit=dev show CACHED. The COPY . . step does not. If you want to see what a full rebuild costs, add --no-cache:
docker build --no-cache -t myapp:1.0 .Common ways the cache breaks or misleads
Stale results from `RUN` commands
Docker compares the text of a RUN command, not its effect. Any command whose output depends on the outside world can be served from cache long after the world has changed. The classic case is package index updates.
FROM debian:12-slim
RUN apt-get update
RUN apt-get install -y curlIf the first line is cached from weeks ago, the second line installs from an old package index and can fail or fetch outdated versions. Combine them in one instruction so they are cached and invalidated together:
FROM debian:12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*Removing the package lists in the same RUN keeps them out of the layer. Deleting files in a later instruction does not shrink the image, because earlier layers are immutable and still contain the data.
Moving tags
FROM node:20-slim resolves to whatever that tag points to when Docker last pulled it. The cache keeps using your local copy until you pull again. To get fresh base images, run docker build --pull. For reproducible builds, pin the base image by digest, for example FROM node:20-slim@sha256:..., and update the digest deliberately.
Copying too much
Every file in the COPY source counts toward the checksum. If COPY . . includes .git, log files, or build output, then changes to those files bust the cache even though they have nothing to do with your application. A .dockerignore file removes them from the context, which is covered in the next chapter.
Build arguments
An ARG value is part of the cache key for instructions that use it. A build argument that changes on every build, such as a timestamp or commit hash, invalidates every later RUN that sees it. Declare such arguments as late as possible in the Dockerfile, after the expensive steps.
Too many or too few layers
Merging unrelated commands into one huge RUN reduces cache reuse, because a change to any part reruns all of it. Splitting a single logical operation across several RUN lines can leave junk in intermediate layers. A good rule is to group commands that must succeed or fail together, such as update then install then clean, and keep independent concerns in separate instructions.
Two practical techniques
Lockfiles make the dependency layer meaningful
Caching the install layer is only safe if the manifest fully describes what gets installed. Use npm ci with a committed package-lock.json, pip install -r requirements.txt with pinned versions, or go mod download with go.sum. Without a lockfile, a cached layer may hold older versions than a fresh build would, and the result depends on when the layer was last built.
Separate rarely changing assets from code
The same ordering idea applies beyond dependencies. If your app has a large model file or dataset that changes monthly, copy it in its own COPY before the source code. Frequent code edits then leave that layer cached.
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY models/ ./models/
COPY src/ ./src/
CMD ["python", "src/main.py"]Here a code change in src/ reruns only the last COPY. A new model reruns the models/ copy and the source copy. A new dependency reruns everything from the install step down.
Checking layers after the build
Use docker history to see the layers of an image and their sizes. It helps you find the step that makes the image large or the layer that changes most often.
docker history myapp:1.0Each row is one instruction. A large layer after a frequently changing step is a sign that your ordering can be improved.
Summary of rules
- A cache miss invalidates every later instruction, so put stable steps first.
- Copy dependency manifests, install, then copy source.
- Combine commands that depend on each other, such as
apt-get updateandapt-get install. - Clean up in the same
RUNthat created the files. - Use
--pullor digests to control base image freshness, and--no-cacheto force a full rebuild. - Declare frequently changing
ARGvalues late.
Exercise
A Dockerfile has COPY . . on line 3 followed by RUN pip install -r requirements.txt on line 4. You change one line in app.py and the pip install runs again, taking two minutes. Rewrite lines 3 and 4 so that editing app.py does not rerun the install, and explain why the new order works.
Show answer
Use COPY requirements.txt ./ then RUN pip install -r requirements.txt then COPY . .. The install layer's cache key now depends only on the text of the instruction and the checksum of requirements.txt. Editing app.py changes only the later COPY . . layer, so Docker reuses the cached install layer and reruns only the final copy and anything after it.
Exercise
Why can RUN apt-get update on its own line, followed by RUN apt-get install -y curl on the next, produce an outdated install weeks later? What is the fix?
Show answer
Docker caches a RUN layer by its command text, not by what the command downloads. The apt-get update layer is a cache hit as long as the earlier layers are unchanged, so the package index inside it can be weeks old. If the install line changes, it runs against that stale index. The fix is to join them in one instruction, RUN apt-get update && apt-get install -y curl, so both are cached and invalidated together.