Sub topic 5
Why one changed step rebuilds everything after it
This chapter explains the cache invalidation cascade. It assumes you can read a Dockerfile, run docker build, and know that an image is a stack of layers. It also assumes you know that each cache check compares an instruction and its inputs with an earlier build. The next chapter uses this behavior to reorder instructions.
The rule in one sentence
When a step is a cache miss, Docker runs that step again. Every step after it is also run again, even if its own instruction and files have not changed.
The build cache is a chain, not a set of independent entries. Each layer is built on top of the layer before it, so a step's cache entry is only valid if its parent layer is the exact one used when the entry was created.
Why the cascade happens
A layer stores the filesystem changes made by one step. Those changes were computed against a specific starting filesystem, which is the result of all earlier steps. If an earlier step produces a different result, the starting point for the next step has changed. Docker cannot know whether the next step would produce the same output, so it does not assume that it would.
A cache lookup for a step therefore depends on two things:
- The parent layer (or, in BuildKit's terms, the cache key of the previous step).
- The step itself: the instruction text and, for
COPYandADD, the content of the files being copied.
If the parent changes, the key changes, and the lookup misses. That miss gives the next step a new parent, so its lookup misses too. The effect passes down the whole chain.
A worked example
Use the first Dockerfile from this tutorial's plan, but with a poor instruction order:
FROM node:20-slim
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run build
CMD ["node", "dist/server.js"]Build it once, then change a single line in src/server.js and build again:
docker build -t myapp:dev .
echo "// touched" >> src/server.js
docker build -t myapp:dev .The second build has this outcome:
| Step | Result on second build | Reason |
|---|---|---|
| `FROM node:20-slim` | Cache hit | Same base image |
| `WORKDIR /app` | Cache hit | Same instruction, same parent |
| `COPY . .` | Cache miss | The content of `src/server.js` changed |
| `RUN npm ci` | Rebuilt | The parent layer changed |
| `RUN npm run build` | Rebuilt | The parent layer changed |
| `CMD` | Metadata only | No filesystem layer to rebuild |
The npm ci step reinstalls every dependency. Its instruction text is the same as before, and package-lock.json did not change. The cascade still forces it to run, because COPY . . sits above it in the chain.
What counts as a miss
Knowing the trigger for each instruction type lets you predict a cascade before you build.
RUN: with the classic builder and with BuildKit, the cache key is the command string and the parent. Docker does not look at what the command does. ARUN apt-get updateis a hit on every build, even months later, until something above it changes.COPYandADD: the key includes a checksum of the copied file contents and relevant metadata such as permissions. Changing a timestamp alone does not cause a miss, but changing content or mode does.ARGandENV: changing the value of a build argument or environment variable invalidates the cache for the first step that uses it. Steps after that are rebuilt through the chain.FROM: if the base image tag now points to a different digest and you pulled it (for example with--pull), the first step changes and everything rebuilds.- Metadata instructions such as
CMD,ENTRYPOINT,EXPOSE, andLABEL: they change image configuration, not files. Changing one still changes the chain, so any later steps lose their cached result.
The `ARG` trap
Build arguments are a common source of surprise cascades. This Dockerfile embeds the git commit early:
FROM python:3.12-slim
ARG GIT_SHA
LABEL commit=$GIT_SHA
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .The LABEL instruction uses GIT_SHA. Every new commit gives a new value, so the LABEL step misses on every build. The pip install step comes after it, so it is also rebuilt every time. Moving ARG GIT_SHA and the LABEL to the end of the file removes that cascade:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
ARG GIT_SHA
LABEL commit=$GIT_SHANow a new commit only invalidates the final LABEL step, plus the COPY . . step if source files changed.
Cases where the cache does not notice a change
The cascade protects correctness only for inputs that Docker can see. Two cases go the other way, where a stale step is reused when you expected a rebuild.
- Network content.
RUN curl -fsSL https://example.com/latest.tar.gz | tar -xzhas the same command text every time. Docker reuses the cached layer even if the remote file changed. - Package indexes.
RUN apt-get updateon its own line is cached. A laterRUN apt-get install -y curlmay then use an old index and fail with a "package not found" error. This is why the plan's second example combinesupdate,install, and cleanup in oneRUN.
To force a fresh run, use one of these options:
# Ignore the cache for the whole build
docker build --no-cache -t myapp:dev .
# Re-pull the base image and keep the rest of the cache logic
docker build --pull -t myapp:dev .You can also pass a build argument that changes on purpose, such as a date, and place it just before the step you want to refresh. The cascade then does the rest.
Reading the cascade in build output
BuildKit prints CACHED next to steps that were reused. The first step without that marker is where the cascade began:
docker build --progress=plain -t myapp:dev .Look for output similar to this:
#5 [2/5] WORKDIR /app
#5 CACHED
#6 [3/5] COPY . .
#6 DONE 0.2s
#7 [4/5] RUN npm ci
#7 DONE 18.4sEverything from COPY . . onward ran. The line to investigate is the first one with no CACHED marker, because the later misses are a result of it. Fixing a later step will not help if an earlier step keeps missing.
Independent stages and parallel steps
In a multi-stage build, the cascade follows the dependency graph of the stages and does not apply to the whole file. A miss in one stage invalidates later steps in that stage. It also invalidates any stage that copies from it with COPY --from. A stage that does not depend on it keeps its cache. BuildKit can also skip stages that the target does not need, and it can build independent stages at the same time.
Common mistakes
- Putting
COPY . .before dependency installation. Any source edit then reinstalls all dependencies. - Changing a
RUNcommand text slightly, for example whitespace in a shell line. The text is the key, so this is a miss. - Using a volatile value early, such as a timestamp
ARGor aCOPYof a file that changes each build (a generated version file, or.gitcopied into the context). - Assuming that a cache hit means the result is current. A hit only means the key matched.
Exercise
A Dockerfile has these steps in order: FROM, WORKDIR, ARG BUILD_DATE, LABEL built=$BUILD_DATE, COPY package.json package-lock.json ./, RUN npm ci, COPY . .. You build with a new BUILD_DATE each day and change no files. Which steps are cache hits, and how would you change the file so that npm ci stays cached?
Show answer
FROM and WORKDIR are hits. LABEL misses because its BUILD_DATE value changed. The COPY of the manifests, RUN npm ci, and COPY . . are also rebuilt, because their parent layer changed. Move ARG BUILD_DATE and the LABEL to the end of the Dockerfile. Then only the final LABEL step runs when the date changes.
Exercise
You change only a comment in README.md, and the Dockerfile has COPY . . followed by RUN npm run build. Does the build step rerun? Name one way to prevent it.
Show answer
Yes. COPY . . includes README.md, so its content checksum changes and the step misses. npm run build then reruns because its parent changed. You can add README.md to .dockerignore so it is not part of the build context, or copy only the directories that the build needs, such as COPY src ./src.