Sub topic 6
Ordering instructions to keep the cache warm
This chapter assumes you can read and write a simple Dockerfile and have run docker build. It also assumes you know that a changed build step invalidates the steps after it. The previous chapter explained that cascade. This chapter shows how to arrange a Dockerfile so the cascade starts as late as possible.
The ordering principle
The build cache is checked from the top of the Dockerfile to the bottom. The first step that misses the cache forces every later step to run again. So the cost of a change depends on where it lands in the file.
The rule that follows is simple: put the steps that change rarely first, and the steps that change often last.
Think about what changes during normal development:
- Base image tag: almost never.
- System packages: occasionally.
- Dependency manifests (
package.json,requirements.txt,go.mod): a few times a week. - Application source code: many times a day.
A good Dockerfile follows that order from top to bottom.
A slow Dockerfile
This Node.js example is common and has a flaw:
FROM node:20-slim
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run build
CMD ["node", "dist/server.js"]COPY . . copies the whole project, including the source files you edit constantly. Docker compares the copied files with the cached layer. If any file differs, that step misses the cache, and so do npm ci and npm run build after it. Changing one line in a source file reinstalls every dependency.
Split the copy in two
npm ci only needs the manifest files to do its work. Copy those first, install, and only then copy the rest:
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]Now the first COPY only contains two files. When you edit source code, those two files are unchanged, so the COPY step and RUN npm ci are cache hits. The cache first misses at COPY . ., so only that step and npm run build run again.
The same pattern works in every ecosystem. Copy the files that describe dependencies, run the install, then copy the source.
| Ecosystem | Copy first | Install step |
|---|---|---|
| Node.js | `package.json`, `package-lock.json` | `npm ci` |
| Python | `requirements.txt` | `pip install -r requirements.txt` |
| Go | `go.mod`, `go.sum` | `go mod download` |
| Ruby | `Gemfile`, `Gemfile.lock` | `bundle install` |
Why `npm ci` and lock files matter here
The cache decision for a COPY step depends on the content of the files, not their names or timestamps. If you copy only package.json and skip the lock file, the install step can still be cached, but you lose reproducibility. A new dependency version may be published without any change to your files, and the cached layer will keep the old one. Copy the lock file and use a command that honors it, such as npm ci.
The cache also does not know about the outside world. A RUN step is a cache hit when its command text and the parent layer are the same, even if the network would now return different results. This leads to the next problem.
Combine update and install in one step
Package indexes are a classic stale-cache trap. Compare these two forms:
# Risky: two separate steps
RUN apt-get update
RUN apt-get install -y curlThe first step has the same command text every time, so it stays cached for weeks. Later you add a package to the second line. That step misses the cache and runs, but it uses the old package index saved in the cached apt-get update layer. Installs can fail with "package not found" errors because the index lists versions that no longer exist.
Put both commands in one RUN, and remove the index files in the same step:
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*Now any change to the package list changes the command text, so the update runs fresh each time. Deleting the index files in the same RUN also keeps them out of the layer entirely, which a later chapter on layer size explains.
Placing system packages
System packages usually change less often than dependency manifests, so they belong above the manifest copy:
FROM python:3.12-slim
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpq5 \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]The order is base image, system packages, dependencies, source, then runtime metadata. Each step is more volatile than the one before it.
Which instructions are safe to place last
Instructions that only add metadata, such as CMD, ENTRYPOINT, EXPOSE, and LABEL, are cheap to rebuild because they create no filesystem content. Even so, the cache still treats them as steps. Putting a LABEL with a build timestamp or commit hash near the top invalidates everything below it:
# Bad: the value changes on every build
ARG GIT_SHA
LABEL commit=$GIT_SHA
COPY package.json package-lock.json ./
RUN npm ciMove values that change on every build to the end of the file:
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
ARG GIT_SHA
LABEL commit=$GIT_SHA
CMD ["node", "dist/server.js"]The same applies to ARG values used in a RUN command. A changed build argument invalidates the first step that uses it, and everything after.
Verify the order with the build output
Do not trust the ordering by reading alone. Build twice, edit a source file, and build again:
docker build -t myapp:dev .
echo "// touch" >> src/index.js
docker build -t myapp:dev .With BuildKit, the output marks reused steps as CACHED. After the edit, you should see COPY package.json ... and RUN npm ci marked CACHED, and the COPY . . step executed. If npm ci runs, something above it changed. Common causes are:
- A file you did not expect is part of the earlier
COPY, such as a wildcard likeCOPY package*.json ./matching more files than intended. - An
ARGorENVwith a changing value appears before the install. - A generated file, such as a version stamp, is copied before the install.
Trade-offs and limits
Ordering has costs and edge cases.
- Readability versus caching. Splitting a
COPYin two adds a line, but the saved minutes per build make it worth it for any project with a slow install. - Many small
RUNsteps versus one large step. Separate steps give finer cache granularity, because a change only reruns what follows. One combined step reduces the number of layers and lets you clean up in the same layer. Combine commands that must stay consistent with each other, likeapt-get updateandinstall. Keep slow, independent steps separate. - Ordering cannot fix a changing manifest. If you add a dependency every day, the install step reruns every day. For that case, BuildKit cache mounts, covered later, keep the package manager's download cache between builds.
- Monorepos. Copy only the manifest of the package you are building, not the whole workspace, or an edit to any package busts the cache.
Summary of the technique
- Start from a pinned base image.
- Install system packages in one
RUNthat updates, installs, and cleans up. - Copy dependency manifests and lock files only.
- Run the dependency install.
- Copy the source code.
- Run the build.
- Set metadata and values that change per build last.
Exercise
A Dockerfile has COPY . . followed by RUN pip install -r requirements.txt. Every source edit reinstalls all packages. Rewrite the two lines so that editing source code does not rerun pip install, and explain why the new order works.
Show answer
Use COPY requirements.txt ., then RUN pip install -r requirements.txt, then COPY . .. The first COPY only includes requirements.txt, so its cache check depends only on that file's content. When you edit source code, requirements.txt is unchanged, so both the first COPY and the pip install are cache hits. The first cache miss is now the later COPY . ., so only the steps after it rerun.
Exercise
You have RUN apt-get update on one line and RUN apt-get install -y git on the next. Months later you add jq to the install line, and the build fails with "Unable to locate package". Why did that happen, and how do you fix it?
Show answer
The apt-get update step has unchanged command text, so it stayed cached and kept the months-old package index. Only the changed install step reran, and it used that stale index. Fix it by combining them: RUN apt-get update && apt-get install -y --no-install-recommends git jq && rm -rf /var/lib/apt/lists/*. Now any change to the package list changes the whole command, so the update reruns too.