Docker multi-stage builds: smaller, faster, and more secure images
How to separate build and runtime to shrink your image, reduce the attack surface, and speed up deployments.
Containers▣Containers
$ docker build -t api:slim .▍A 1.2 GB image packed with a compiler, package cache, and debugging tools has no business going to production. With multi-stage builds, you compile in one stage and copy only the final artifact into a lean image.
Go example
# Build stage
FROM golang:1.23 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/api ./cmd/api
# Final stage
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
USER nonroot:nonroot
ENTRYPOINT ["/api"]
The final image contains only the binary and the bare minimum needed to run it — no shell and no package manager.
Benefits
- Size: from hundreds of MB down to a few MB.
- Security: fewer packages means fewer CVEs in your scanners.
- Speed: faster pulls, which speeds up pod scaling.
Extra best practices
- Copy dependency files first to take advantage of layer caching.
- Use
.dockerignoreto keepnode_modules,.git, and the like out of the build context. - Run as a non-root user.
- Pin the base image by digest in critical environments.
- Scan images in CI with Trivy or Grype.
For interpreted languages such as Node.js or Python, the logic is the same: install build dependencies in the first stage and copy only what’s needed into a slim image.