← All insightsContainers

Dockerfile best practices for small, fast, secure images

CodeWizard Academy · 4 July 2025 · 3 min read · Intermediate

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

dockerfile
# 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
bash
# build-time secrets without leaking them into layers
RUN --mount=type=secret,id=npmrc npm ci
A 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.

Like where this is going?

Get hands-on help from the engineers who write these posts.

Book a free consult