Sub topic 9
Ordering Dockerfile instructions for cache reuse
This chapter assumes you can write a basic Dockerfile, know what a layer is, and have read the earlier chapters on how the layer cache works and why CI builds start cold. A remote cache can only restore layers that are still valid. Instruction order decides how many layers stay valid after a change.
The rule: least-changing first
BuildKit builds layers in order. If the inputs to one instruction change, that layer and every layer after it are rebuilt. Layers before it can still come from cache.
For COPY and ADD, the inputs are the checksums of the copied files. For RUN, the input is the command text plus the layers below it. Editing one source file therefore invalidates a COPY . . instruction and everything below it.
The practical rule is to put things that rarely change at the top and things that change on every commit at the bottom.
A cache-friendly example
Here is a Node.js build that follows the rule.
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/index.js"]The build proceeds like this:
FROMandWORKDIRchange only when you change the base image or path.COPY package.json package-lock.json ./is invalidated only when a manifest changes.RUN npm ciis the slow step. It stays cached as long as the manifests are identical.COPY . .changes on almost every commit, so it is rebuilt.RUN npm run buildruns after it and is rebuilt as well.
A commit that edits only application code reuses the npm ci layer. In CI, that layer is restored from the remote cache instead of being downloaded and installed again.
The anti-pattern
Compare this version.
FROM node:20-slim
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run build
CMD ["node", "dist/index.js"]Here COPY . . comes first. Any change to any file produces a new layer checksum. That invalidates npm ci, even when the dependencies are unchanged. The remote cache is still exported and imported, but the cache key never matches, so every build repeats the install.
Other habits that keep cache valid
- Add a
.dockerignorefile. Exclude.git,node_modules, build output, and logs. Otherwise a change in those paths alters theCOPY . .checksum for no reason. - Pin base images. A floating tag such as
node:latestcan change under you. Use a specific version, or a digest if you need exact reproducibility. - Avoid volatile values early. A
RUNthat writes a timestamp, or anARGsuch as a commit SHA used near the top, invalidates everything below it. Declare suchARGvalues as late as possible. - Combine commands that belong together. Run
apt-get updateandapt-get installin oneRUN, so a stale package index is never cached separately from the install. - Use multi-stage builds. Separate stages for dependencies, build, and runtime let BuildKit skip stages whose inputs did not change. With
mode=max, intermediate stages are exported too, so they can be restored.
Checking your ordering
You can test an ordering locally. Build once, change a single source file, and build again. Only the steps after COPY . . should run. The chapter on checking cache use shows how to read the CACHED markers in the output.
Exercise
A Dockerfile starts with COPY . . followed by RUN pip install -r requirements.txt. Builds in CI reinstall all packages on every commit, even though requirements.txt rarely changes. How do you fix it?
Show answer
Copy only requirements.txt first, run pip install -r requirements.txt, and then run COPY . .. The install layer's inputs are now just the requirements file, so it stays cached until that file changes. Adding a .dockerignore file also keeps unrelated files from changing the later copy step.