← All articles
· 2 min read

Docker layer caching, demystified

Most slow image builds come from one misplaced COPY. Here is how the cache actually keys layers, and the two rules that keep rebuilds fast.

A clean build takes four minutes, a one-line change rebuilds in four minutes too, and everyone shrugs and blames Docker. Docker is not the problem. The cache is working exactly as designed; the Dockerfile is just feeding it badly.

Each instruction in a Dockerfile produces a layer. The cache key for a layer is the instruction text plus, for COPY and ADD, a checksum of the files being copied. The moment one layer misses, every layer after it is rebuilt. So the order of instructions is the whole game: put the things that rarely change first.

The classic mistake:

FROM golang:1.23
WORKDIR /app
COPY . .                 # any source change busts the cache here
RUN go mod download      # ...so deps re-download every build
RUN go build -o /bin/app ./cmd/app

Copy the dependency manifest on its own first. It changes far less often than your source, so the expensive download layer stays cached across ordinary commits.

Dockerfile
FROM golang:1.23 AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download      # cached until go.mod/go.sum change
COPY . .
RUN go build -o /bin/app ./cmd/app

FROM gcr.io/distroless/base-debian12
COPY --from=build /bin/app /app
ENTRYPOINT ["/app"]

Now a code-only change reuses the dependency layer and the build drops to seconds. Two more levers: a multi-stage build keeps the toolchain out of the final image, and a .dockerignore that excludes .git, test fixtures and local artefacts stops unrelated files from busting COPY . .. Measure before and after with docker build --progress=plain; the lines that say CACHED are the ones doing their job.