StackPractices
intermediate By Mathias Paulenko

Distroless Docker Images with Multi-Stage Builds

Build minimal, shell-free production images by pairing multi-stage builds with distroless bases — Go, Node.js, Python, and Java examples.

Topics: devops

Overview

A multi-stage build compiles your app in a full-fat builder image — compilers, package managers, caches and all — then copies only the finished artifact into a second, minimal stage. Distroless images take that minimal stage to its limit: they’re Google’s runtime-only bases that ship your app’s dependencies and nothing else. There’s no shell, no apt, no coreutils, not even sh — an attacker who lands inside finds nothing useful to run.

The payoff is real and measurable: a Go service drops from ~800MB on golang:1.22 to ~15MB on static-debian12, and a Node app from ~1GB to ~150MB. Smaller pull times, smaller registry bills, and a vulnerability surface so thin that most CVE scanners come back nearly empty. Every example below runs on the gcr.io/distroless/* family, with Alpine and Chainguard variants where they make more sense.

Runnable Dockerfiles for every example live in the companion repo.

For build-speed tuning and layer-caching tricks beyond distroless, the companion recipe is multi-stage build optimization — this page is specifically about minimal, shell-free runtime bases.

When to Use

  • Production services where image size translates to pull speed and storage cost
  • Security-sensitive workloads — with no shell inside, docker exec … sh and most post-exploitation tooling are simply absent
  • CI/CD pipelines where compilers and package managers must stay out of the shipped artifact
  • Anything running in Kubernetes or serverless platforms where cold-start pull time matters

When NOT to Use

  • Dev or debug containers — you’ll want a shell, a package manager, and strace
  • Apps that shell out to OS tools (imagemagick, ffmpeg, git) — distroless has none
  • Apps needing glibc-linked binaries that you can’t rebuild — use base or cc distroless variants, or just use debian-slim
  • Quick internal tooling where 200MB of image size buys you nothing

Solution

Basic multi-stage build (Go)

# Stage 1: Builder
FROM golang:1.22-alpine AS builder

WORKDIR /app

# Cache dependencies
COPY go.mod go.sum ./
RUN go mod download

# Build
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server ./cmd/server

# Stage 2: Distroless final
FROM gcr.io/distroless/static-debian12

COPY --from=builder /app/server /server

EXPOSE 8080

USER nonroot:nonroot

ENTRYPOINT ["/server"]

CGO_ENABLED=0 isn’t optional here — static-debian12 contains no libc at all, so only a fully static Go binary will start. The -ldflags="-s -w" pair strips the symbol table and DWARF debug info, which takes another ~30% off the binary. And USER nonroot:nonroot resolves to uid 65532, a user distroless ships in its minimal /etc/passwd; running as root inside a tool-free container is still bad practice — see the hardening checklist for the rest of the surface.

Multi-stage build for Node.js

# Stage 1: Build
FROM node:22-alpine AS builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

# Stage 2: Production
FROM node:22-alpine AS production

WORKDIR /app

COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force

COPY --from=builder /app/dist ./dist

USER node

EXPOSE 3000

CMD ["node", "dist/index.js"]

Multi-stage with distroless for Node.js

# Stage 1: Build
FROM node:22 AS builder

WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Stage 2: Distroless
FROM gcr.io/distroless/nodejs22-debian12

WORKDIR /app

COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./

USER nonroot:nonroot

EXPOSE 3000

CMD ["dist/index.js"]

Two details worth knowing about nodejs22-debian12: the image’s entrypoint is already node, so CMD gets just the script path — writing CMD ["node", "dist/index.js"] would try to exec node node. And unlike the Alpine variant above, there are no npm ci shenanigans in the final stage: node_modules comes across whole from the builder, dev dependencies included unless you prune them there first.

Multi-stage build for Python

# Stage 1: Builder
FROM python:3.12-slim AS builder

WORKDIR /app

RUN pip install --no-cache-dir uv

COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev

COPY . .
RUN uv run build

# Stage 2: Production
FROM python:3.12-slim AS production

WORKDIR /app

COPY --from=builder /app/.venv ./.venv
COPY --from=builder /app/dist ./dist

ENV PATH="/app/.venv/bin:$PATH"

RUN useradd -m appuser
USER appuser

EXPOSE 8000

CMD ["python", "-m", "myapp"]

Python is the awkward case for true distroless: the interpreter needs its stdlib, so you carry python:3.12-slim as the runtime (~50MB) rather than a real distroless base. The multi-stage part still pays off — pip, uv, wheels and build headers stay in the builder. For genuinely minimal Python runtimes, look at gcr.io/distroless/python3-debian12 (experimental) or compile to a binary with PyInstaller/Nuitka and then use static.

Multi-stage build for Java (Gradle)

# Stage 1: Build
FROM gradle:8-jdk21 AS builder

WORKDIR /app

COPY settings.gradle build.gradle ./
COPY gradle ./gradle
RUN gradle dependencies --no-daemon

COPY src ./src
RUN gradle bootJar --no-daemon

# Stage 2: Runtime
FROM eclipse-temurin:21-jre-alpine

RUN addgroup -S appgroup && adduser -S appuser -G appgroup

COPY --from=builder /app/build/libs/*.jar /app/app.jar

USER appuser

EXPOSE 8080

ENTRYPOINT ["java", "-jar", "/app/app.jar"]

Java needs a JRE, so eclipse-temurin:21-jre-alpine (~90MB) is the pragmatic floor — or gcr.io/distroless/java21-debian12 if you want the shell-free variant. The builder stage still earns its keep by keeping Gradle, its daemon cache, and the JDK out of the shipped image.

Named stages for selective copying

# Stage 1: Install dependencies
FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci

# Stage 2: Build
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# Stage 3: Test
FROM node:22-alpine AS tester
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run test

# Stage 4: Production
FROM node:22-alpine AS production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY package*.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]

Only stages the final FROM actually references make it into the image — deps and tester are scaffolding that produces layers but ships nothing. That also means docker build --target tester gives you a test image on demand without polluting production.

Using .dockerignore

# .dockerignore
node_modules
dist
.git
*.md
.env*
coverage
.vscode
.idea

This file gates what goes into the build context, not the image — the win is a faster COPY . ., plus layer cache stops breaking every time a stray node_modules/ or .env changes between builds. It belongs in every multi-stage Dockerfile, not just distroless ones.

Distroless with health checks

FROM gcr.io/distroless/static-debian12

COPY --from=builder /app/server /server

# Distroless has no shell — the check must be a binary your app ships
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD ["/server", "--healthcheck"]

USER nonroot:nonroot

EXPOSE 8080

ENTRYPOINT ["/server"]

The catch: no shell means no curl or wget for the check, so your binary needs its own --healthcheck subcommand (Go: flag; Node: hit /health yourself). And remember plain docker run reports unhealthy but never restarts the container — Swarm, Kubernetes, or autoheal act on it; details in the health check recipe.

Build with BuildKit cache mounts

# syntax=docker/dockerfile:1.7

FROM golang:1.22-alpine AS builder

WORKDIR /app

COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
    go mod download

COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server ./cmd/server

FROM gcr.io/distroless/static-debian12
COPY --from=builder /app/server /server
USER nonroot:nonroot
ENTRYPOINT ["/server"]

Cache mounts persist /go/pkg/mod and the build cache between builds without baking them into any layer — dependency downloads drop to near-zero on rebuilds. Same trick for npm (--mount=type=cache,target=/root/.npm) and pip (target=/root/.cache/pip).

Variants

Distroless with CA certificates

FROM gcr.io/distroless/static-debian12:nonroot

COPY --from=builder /app/server /server

ENTRYPOINT ["/server"]

static-debian12 already ships CA certs and the nonroot passwd entry — you only need to copy certificates yourself when your app calls internal services with private CA roots, in which case layer them on top: COPY internal-ca.crt /usr/local/share/ca-certificates/.

Using Chainguard images

# Chainguard — minimal, no shell, rebuilt daily against new CVEs
FROM cgr.dev/chainguard/go:1.22 AS builder

WORKDIR /app
COPY . .
RUN go build -o /server ./cmd/server

FROM cgr.dev/chainguard/static:latest

COPY --from=builder /server /server
USER nonroot
ENTRYPOINT ["/server"]

Chainguard images are distroless-style bases rebuilt daily — static and go are free-tier images; most others need a paid pull subscription. Worth knowing before you standardize on them in CI.

Alpine-based minimal image (alternative to distroless)

FROM golang:1.22-alpine AS builder

WORKDIR /app
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /server ./cmd/server

FROM alpine:3.20

RUN apk --no-cache add ca-certificates && \
    adduser -D -h /app appuser

COPY --from=builder /server /app/server

USER appuser
WORKDIR /app
ENTRYPOINT ["/server"]

Pick Alpine over distroless when you need a shell for debugging or apk for a runtime dependency — you trade ~5MB of extra surface (busybox, apk, musl) for a lot of operability, the honest middle ground between slim Debian and nothing at all.

Debug distroless image

# :debug tag adds busybox — shell access when you need it
FROM gcr.io/distroless/static-debian12:debug

COPY --from=builder /app/server /server

USER nonroot:nonroot
ENTRYPOINT ["/server"]

Every distroless variant ships a :debug tag with busybox bolted on — same image plus sh, ls, cat, and friends. For incidents, build a second target on :debug, or docker cp tools into the running container. Keep :debug out of production — a shell inside defeats the whole point.

Explanation

Underneath, the mechanism is nothing fancy: every FROM begins a new image and COPY --from=<stage> is the only bridge between them. Whatever a stage fails to export is gone — toolchain, layer cache, everything dies at the final FROM.

flowchart diagram: subgraph Builder[

What’s actually inside static-debian12: glibc, CA certificates, tzdata, and an /etc/passwd with root (0) and nonroot (65532) — that’s the whole filesystem. base-debian12 adds a bit more libc glue for dynamically-linked apps; cc carries libstdc++ for C++; java21, nodejs22, and python3 add their runtimes. Every variant enforces the same rule — only your app’s runtime earns a place in the image.

Distroless vs the alternatives:

  • vs scratch: scratch is truly empty — no certs, no passwd, no glibc. Distroless is scratch plus the few bytes any real app demands. Reach for scratch only when you’re hand-assembling images and want byte-level control.
  • vs Alpine: Alpine keeps apk and busybox — debuggable, but ~40% more CVE surface in practice.
  • vs slim Debian: debian:bookworm-slim is ~80MB with bash and dpkg — fine, but it’s not “minimal” in the security sense.
  • vs Chainguard: same philosophy, paid-vendor cadence.

Verifying the shrink

docker build -t myapp:fat -f Dockerfile.old .
docker build -t myapp:distroless .
docker images myapp --format "{{.Tag}}: {{.Size}}"
# fat:        812MB
# distroless: 14MB

If the distroless image won’t start, it’s almost always one of three things: a dynamically-linked binary on static (run ldd in the builder to check), a missing CA cert for outbound TLS, or ENTRYPOINT/CMD written for a shell that isn’t there.

Best Practices

  • Go binaries need CGO_ENABLED=0 — static-debian12 ships no libc, so anything cgo-linked fails to start.
  • Strip with -ldflags="-s -w" — debug info is dead weight in a shell-free image.
  • Run as USER nonroot:nonroot (uid 65532) — it’s already in the image’s passwd file.
  • .dockerignore from day one — the build context isn’t the image, but it poisons layer cache.
  • Pin base image tags (golang:1.22-alpine, debian12) — :latest is a moving target.
  • Use BuildKit cache mounts for package-manager caches — the builder wants speed; only the final stage cares about size.
  • Dependencies first, source second — COPY go.mod go.sum ./ before COPY . . keeps the expensive layers cached.
  • docker buildx build --platform linux/amd64,linux/arm64 for multi-arch — distroless variants are published per-arch.

Common Mistakes

  • Skipping the multi-stage split — compilers and package managers ride along to production and the image balloons 10-100x.
  • :latest base tags — the image you tested isn’t the one you deploy.
  • Root inside distroless — the attack surface is small, not zero; use USER nonroot:nonroot.
  • No .dockerignore — node_modules and .git ride into every build.
  • Shipping debug info — -s -w buys a free ~30% on Go.
  • docker exec -it … sh muscle memory on a shell-free image — the :debug tag exists for exactly this.
  • Copying stock CA certs into static-debian12 — they ship with the image; only private roots belong in your Dockerfile.
  • Assuming health checks restart containers — docker run reports unhealthy and does nothing with it.

Further Reading

See Also

Frequently Asked Questions

What is a distroless image?

A Docker base image with only your app's runtime dependencies — no shell, no package manager, no OS utilities. Maintained by Google at gcr.io/distroless/*, in variants like static, base, cc, java21, nodejs22, and python3.

How much smaller are multi-stage images?

Typically 10-100x. Ship a Go service on golang:1.22 and you carry ~800MB; the same binary on static-debian12 weighs ~15-20MB. Node.js shows the same pattern — roughly 1GB shrinks to ~150MB on nodejs22-debian12. Measure yours with docker images --format "{{.Size}}" — the win varies with how much junk the builder carried.

Can I debug a distroless container?

Yes — every variant has a :debug tag that adds busybox (gcr.io/distroless/static-debian12:debug). For a running production container, docker cp tools in, or in Kubernetes use an ephemeral debug container attached to the same process namespace.

What's the difference between distroless and Alpine?

Alpine is a minimal Linux distro (~5MB) with apk and a shell — general-purpose. Distroless has neither; it's a runtime, not a distro. Alpine when you need operability, distroless when attack surface and size are the constraint.

How do I add CA certificates to distroless?

You usually don't — static-debian12 already bundles them. For private CAs, copy your root into /usr/local/share/ca-certificates/ or alongside the binary and point SSL_CERT_FILE at it.