Image size is not vanity - it is pull time, cost and attack surface. Most oversized images come from single-stage builds that ship the entire toolchain to production. Multi-stage builds fix that.
A multi-stage build
# build stage has the toolchain
FROM golang:1.22 AS build
WORKDIR /src
COPY go.* ./ && RUN go mod download
COPY . . && RUN CGO_ENABLED=0 go build -o /app ./cmd/server
# runtime stage is tiny and rootless
FROM gcr.io/distroless/static:nonroot
COPY --from=build /app /app
USER nonroot
ENTRYPOINT ["/app"]The rules that matter
- Order layers least- to most-frequently changed for cache hits
- Use a .dockerignore to keep .git and node_modules out of the context
- Run as a non-root USER and prefer distroless/alpine runtimes
- Pin base image tags or digests; never rely on :latest
# build-time secrets without leaking them into layers
RUN --mount=type=secret,id=npmrc npm ciA distroless image with no shell is not just smaller - it removes a whole class of exploits.
Multi-stage plus a non-root, minimal runtime routinely turns a 900MB image into under 30MB, and shrinks what an attacker can do if they get in.