Sub topic 6
Using the build cache well
This chapter assumes you can write a basic Dockerfile and run docker build. It also assumes you know that an image is a stack of layers, covered earlier in this tutorial. Here you will learn how Docker decides to reuse a layer, what makes it rebuild one, and how to order a Dockerfile so that most builds finish in seconds.
How the cache decides
Each instruction in a Dockerfile produces a layer, or a metadata change. Before running an instruction, the builder checks whether it already has a result for the same instruction on top of the same parent. If it does, it prints CACHED and skips the work.
What counts as "the same" depends on the instruction:
| Instruction | Cache key |
|---|---|
| `RUN` | The command text and the parent layer. The builder does not look at what the command does. |
| `COPY`, `ADD` | The parent layer and a checksum of the copied file contents. Modification times are ignored. |
| `ENV`, `ARG`, `WORKDIR`, `LABEL` | The instruction text and the parent layer. |
| `FROM` | The base image that the tag resolves to locally. |
The most important rule is that a cache miss invalidates every instruction after it. Layers are stacked, so a changed layer gives all later layers a new parent. Order your instructions from least likely to change to most likely to change.
The classic mistake
This Dockerfile works but rebuilds everything on each source edit:
FROM golang:1.22
WORKDIR /src
COPY . .
RUN go mod download
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/appCOPY . . brings in every file, including your source code. Edit one .go file and the checksum changes. That layer misses, so go mod download runs again and re-downloads every dependency, even though go.mod did not change.
The fix is to copy only the dependency manifests first, install dependencies, and copy the rest afterward:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.io/distroless/static-debian12
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]Now the go mod download layer depends only on go.mod and go.sum. A source edit misses the cache at COPY . . and rebuilds only the compile step.
The same pattern applies to other ecosystems. For Node.js, copy package.json and the lockfile, run npm ci, then copy the source. For Python, copy requirements.txt, run pip install -r requirements.txt, then copy the source.
Reading the build output
Build the image twice and watch the output. With BuildKit, which is the default builder in current Docker releases, cached steps are marked:
docker build -t myapp:1.0 .
touch cmd/app/main.go
echo "// note" >> cmd/app/main.go
docker build -t myapp:1.0 .On the second build, expect output similar to this:
=> CACHED [build 3/6] COPY go.mod go.sum ./
=> CACHED [build 4/6] RUN go mod download
=> [build 5/6] COPY . .
=> [build 6/6] RUN CGO_ENABLED=0 go build -o /out/app ./cmd/appEvery step before COPY . . is reused. Everything from that step onward runs again.
Keep the context from invalidating layers
A COPY . . instruction checksums everything in the build context. If your context includes .git, log files, or build output, any change to them also causes a miss. A .dockerignore file prevents this:
.git
node_modules
*.log
.envExcluding files also keeps secrets such as .env out of the image, and it makes the context upload smaller.
Cases where the cache is wrong
The builder compares the command text, not the outside world. This causes several well-known problems.
Stale package indexes
Consider this pair of instructions:
FROM debian:12-slim
RUN apt-get update
RUN apt-get install -y curlThe apt-get update layer is cached forever. Later, you add a package to the install line. That line misses the cache, but it runs against the old package index and can fail with "package not found" errors or install outdated versions. Combine the commands in one RUN, and clean up in the same layer:
FROM debian:12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*The cleanup must happen in the same RUN. If you delete the files in a later layer, the earlier layer still contains them, and the image stays large.
Commands that fetch changing content
RUN git clone https://example.com/repo.git or RUN curl -sL https://example.com/latest produce the same command text every time. The cache will serve an old result. Pin to a version or commit in the command text, so a change to the version invalidates the layer. For example, use RUN curl -sL https://example.com/v1.4.2/tool.tgz.
Build arguments
Changing the value of an ARG invalidates the cache for instructions that use it, and for all instructions after it. Declare ARG as late as possible, close to where you use it. Do not put something like ARG BUILD_DATE or a git commit near the top, or every build will start from scratch.
Controlling the cache
Use these flags when you need to override the default behavior:
docker build --no-cache .ignores all cached layers and rebuilds everything.docker build --pull .checks the registry for a newer version of the base image before building. Without it, a tag likegolang:1.22that exists locally is reused even if the registry has a newer one.docker builder pruneremoves unused build cache entries to free disk space.
Cache mounts
Even with good ordering, a change to go.mod forces go mod download to start from an empty module directory. A BuildKit cache mount keeps a directory outside the image layers and reuses it between builds:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -o /out/app ./cmd/appThe cache directories are not part of the final image. A changed dependency list now downloads only the new modules. The compile step also reuses previous compiler results.
Caches in CI
On a fresh CI runner, the local cache is empty, so every build looks cold. BuildKit can export and import the cache through a registry:
docker buildx build \
--cache-from type=registry,ref=registry.example.com/team/myapp:buildcache \
--cache-to type=registry,ref=registry.example.com/team/myapp:buildcache,mode=max \
-t registry.example.com/team/myapp:1.0 --push .With mode=max, the exported cache includes intermediate layers from every stage, not only the final one. This matters for multi-stage builds, where the expensive steps are in earlier stages. Depending on your setup, docker buildx may need a builder that uses the docker-container driver for registry cache export.
Summary checklist
- Put rarely changing instructions first and frequently changing ones last.
- Copy dependency manifests before source code.
- Use
.dockerignoreto keep noise out of the context. - Combine
apt-get updatewith the install in oneRUN. - Pin versions in commands that download content.
- Declare
ARGlate. - Use cache mounts for package downloads and compiler caches.
Exercise
A Dockerfile has COPY . . as its second instruction, followed by RUN npm ci and RUN npm run build. Changing a single README file makes every build re-run npm ci. Explain why, and show how to change the Dockerfile so that a README edit does not re-run npm ci.
Show answer
COPY . . checksums every file in the context, including the README. When the README changes, that layer misses the cache, and every later instruction, including npm ci, misses too. Copy only the dependency files first: COPY package.json package-lock.json ./, then RUN npm ci, then COPY . ., then RUN npm run build. A README edit now misses only at COPY . . and the build step, and npm ci stays cached. Adding .dockerignore entries for files the build does not need, or for *.md, would reduce misses further.
Exercise
Your build contains RUN apt-get update on one line and RUN apt-get install -y curl on the next. Why is this risky, and what is the fix?
Show answer
The apt-get update layer can stay cached for months. When the install line later changes and misses the cache, it runs against the old package index, which can cause missing-package failures or outdated packages. Combine both commands in one RUN apt-get update && apt-get install -y curl, and remove /var/lib/apt/lists/* in that same RUN so the index files do not remain in the layer.