123DevOps··2 min read

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

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

  1. Copy dependency files first to take advantage of layer caching.
  2. Use .dockerignore to keep node_modules, .git, and the like out of the build context.
  3. Run as a non-root user.
  4. Pin the base image by digest in critical environments.
  5. 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.

Get updates on new posts and stay in the loop!