Sub topic 3
Ordering instructions for the build cache
This chapter assumes you can read a simple Dockerfile, run docker build and docker run, and know that an image is made of layers. You will learn how Docker decides to reuse a layer, why instruction order controls build speed, and which mistakes break the cache.
How the cache decides to reuse a layer
Each instruction that changes the filesystem (RUN, COPY, ADD) produces a layer. Before running an instruction, the builder looks for a cached layer with the same parent layer and the same instruction. If it finds one, it reuses it and prints CACHED. If not, it runs the instruction and creates a new layer.
The check differs by instruction:
RUNis compared by its command string. Docker does not look at what the command would download.RUN apt-get updatestays cached even if the package index has changed upstream.COPYandADDare compared by the content of the copied files (checksums), not by timestamps. Changing one byte in one copied file invalidates the layer.ENV,ARG,WORKDIRand other metadata instructions are compared by their text and values.
The most important rule follows from the parent check. Once one layer is invalidated, every later layer is rebuilt, even if its own instruction did not change. The cache is a chain, not a set.
The ordering principle
Put instructions that change rarely at the top and instructions that change often at the bottom. In most projects the order of change frequency is:
- Base image and system packages (change rarely).
- Dependency manifests, such as
package.jsonorrequirements.txt(change occasionally). - Application source code (changes on nearly every commit).
Compare two Node.js Dockerfiles. The first copies everything before installing dependencies:
FROM node:20
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run buildAny edit to any source file changes the COPY . . layer, so npm ci runs again on every build. The second copies only the manifests first:
FROM node:20
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run buildNow npm ci is invalidated only when package.json or package-lock.json changes. A source-only edit reuses the dependency layer and rebuilds just the last two instructions. For a project with hundreds of dependencies this often turns a build of several minutes into one of a few seconds.
The Go example in this tutorial uses the same idea: COPY go.mod go.sum ./ followed by RUN go mod download caches the module download, and COPY . . comes afterward.
Watching the cache work
Build twice and compare the output. With BuildKit, the default builder in current Docker, reused steps are marked CACHED.
docker build -t myapp:dev .
# edit a file under src/, then build again
docker build -t myapp:dev .
# show every step in plain text instead of the compact view
docker build --progress=plain -t myapp:dev .In the second build you should see CACHED next to the FROM, WORKDIR, manifest COPY and npm ci steps, and no CACHED next to the source COPY and everything after it. If a step you expected to be cached reruns, look at the steps above it. The first non-cached step is the cause, and everything below it is a consequence.
To ignore the cache entirely, for example to pick up fresh OS security updates, use docker build --no-cache ..
Combining commands that belong together
A cached RUN is only as fresh as the first time it ran. This causes a classic bug:
RUN apt-get update
RUN apt-get install -y curlIf you later add a package to the second line, the first line is still cached, so the install runs against an old package index and can fail with "package not found" or install stale versions. Put both commands in one RUN so they are cached and invalidated together:
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*The same single instruction also removes the package index in the layer that created it. Deleting files in a later layer does not shrink the image, because the earlier layer still contains them. Chapter topics on layers and image size cover this in more detail.
What silently breaks the cache
Several things invalidate layers in ways that are easy to miss.
Changing files that are copied early
COPY . . copies the whole build context. Log files, local build output, editor swap files and .git metadata all count as content. If any of them changes between builds, the layer is invalidated. The next chapter shows how .dockerignore removes this noise. Until then, the practical rule is to copy only what a step needs: COPY package*.json ./ instead of COPY . . for dependency installation.
Build arguments
An ARG that is declared and then used changes the cache key when its value changes. A common mistake is passing a value that changes on every build, such as a timestamp or commit hash, and declaring it near the top:
FROM node:20
ARG GIT_COMMIT
WORKDIR /app
COPY package*.json ./
RUN npm ciHere the value of GIT_COMMIT is part of the environment for later RUN instructions, so each new commit can invalidate npm ci. Declare volatile arguments as late as possible, after the expensive steps, and use them only in the instructions that need them.
Commands whose result depends on the outside world
Because RUN is compared by text, a command like RUN git clone https://example.com/repo.git or RUN curl -O https://example.com/latest.tar.gz stays cached forever, even when the remote content changes. If you need freshness, pin a version in the command (.../v1.4.2.tar.gz) so that changing the version changes the text, or build with --no-cache for the affected step.
Floating base image tags
FROM node:20 refers to a tag that moves as the maintainers publish updates. Your local copy is reused until you pull a new one, so two machines can have different cached results for the same Dockerfile. Pull explicitly with docker build --pull . in CI to check for a newer base. For reproducible builds, pin to a specific version tag or an image digest.
Cache behavior in multi-stage builds
A multi-stage Dockerfile has a separate chain of layers for each stage. Ordering applies inside every stage. Two points matter in practice:
- A stage is rebuilt only when something it depends on changed. If the final stage does
COPY --from=build /app/dist ./dist, a change in the build stage invalidates thatCOPYand what follows it, but earlier instructions in the final stage (such as installing production dependencies) stay cached. - BuildKit builds only the stages that the target needs, and it can build independent stages in parallel.
This is why the Node.js example in this tutorial runs npm ci --omit=dev in the final stage before COPY --from=build. The slow production install stays cached across source edits, and only the cheap copy of dist changes.
Cache across machines
The local cache lives on one machine. A fresh CI runner starts empty, so every build is a full build unless you export the cache. BuildKit can store cache in a registry:
docker buildx build \
--cache-from type=registry,ref=registry.example.com/myapp:cache \
--cache-to type=registry,ref=registry.example.com/myapp:cache,mode=max \
-t registry.example.com/myapp:latest \
--push .mode=max exports layers from all stages, including intermediate ones, which matters for multi-stage builds. The default, mode=min, exports only layers of the final image, so the build stage would be rebuilt on each fresh runner. Using this form requires a builder that supports cache export. Depending on your setup you may need to create one with docker buildx create --use.
A checklist for ordering
- Put the base image and system packages first.
- Copy only dependency manifests, then install dependencies.
- Copy the rest of the source and build.
- Combine commands that must stay consistent, such as
apt-get updateandinstall, into oneRUN. - Declare volatile
ARGvalues late. - Run
docker build --progress=plainand find the first non-cached step when a build is slower than expected.
Exercise
A Python Dockerfile has COPY . . on one line and RUN pip install -r requirements.txt on the next. Builds reinstall every dependency after each code change. How do you fix the order, and why does the fix work?
Show answer
Copy only requirements.txt first, run pip install -r requirements.txt, and then run COPY . .. The dependency layer is keyed on the content of requirements.txt, so it is reused as long as that file is unchanged. A source edit then invalidates only the later COPY . . layer and the instructions after it.
Exercise
After you add vim to the second line of RUN apt-get update followed by a separate RUN apt-get install -y curl vim, the build fails with "Unable to locate package vim", even though it works on a colleague's machine. What is the cause and the fix?
Show answer
The apt-get update layer is cached from an earlier build, so the package index is old. The install line changed and ran against that stale index. Combine both commands in a single RUN apt-get update && apt-get install -y curl vim, so a change to the package list also reruns the update.