An image is a stack of read-only layers, one per build instruction. When a line changes, that layer and everything after it is rebuilt. That single fact explains almost every slow build.
Order from least to most volatile
Dependencies change rarely, source code changes constantly. Copy the dependency manifest first, download modules, and only then copy the rest of the tree.
FROM golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download # cached until go.mod changes
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app
FROM gcr.example/distroless/static
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]
Before
Every commit invalidated the module download layer. Builds took about three minutes on CI.
After
Only the final two layers rebuild on a code change. Builds take about twenty seconds.
Multi-stage builds also keep compilers and caches out of the image you ship, which shrinks it and removes a whole class of security findings.
