StackPractices
intermediate By Mathias Paulenko

Docker Multi-Stage Build Optimization for Smaller Images

Cut Docker image size and build time with multi-stage builds, smarter layer ordering, BuildKit cache mounts, and a lean .dockerignore.

Topics: devops

Overview

A multi-stage Dockerfile builds your app in a toolchain-rich stage and copies only the artifacts it needs into a slim final stage. Done well, that alone cuts images 80-90 percent — a Go service drops from ~1.2GB on golang:1.22 to ~15MB on scratch. But size is only half the win: the same file, ordered badly, also rebuilds your dependency layer on every single commit. This recipe covers both halves — shrinking the image that ships and the time it takes to build.

Runnable Dockerfiles for every example live in the companion repo. For the deep dive on shell-free minimal bases, see distroless multi-stage builds — this page stays on the optimization side: layer order, caches, and build speed.

When to Use

  • Your image is over ~500MB for a simple app, or docker images surprises you
  • Compilers, SDKs, or node_modules ship to production
  • CI builds take minutes because dependency install re-runs on every commit
  • Build and runtime need different bases — golang to compile, scratch or distroless to run

When NOT to Use

  • One-file scripts and throwaway containers — a second stage buys nothing
  • Apps that genuinely need their toolchain at runtime (some compilers-as-a-service, plugin hosts)
  • If your only problem is cache misses in CI, --mount=type=cache alone may fix it without restructuring

Solution

Node.js multi-stage build

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

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

# Stage 2: Production
FROM node:20-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"]

npm ci --omit=dev in the final stage reinstalls only production deps — devDependencies never cross the FROM. Pruning node_modules in the builder and copying it wholesale looks shorter but drags dev deps along and breaks layer cache differently; reinstalling from lockfile is cleaner.

Python multi-stage with a minimal runtime

# Stage 1: Build dependencies
FROM python:3.11-slim AS builder

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir --target=/opt/deps -r requirements.txt

# Stage 2: Runtime
FROM gcr.io/distroless/python3-debian12 AS runtime

WORKDIR /app

COPY --from=builder /opt/deps /opt/deps
COPY . .

ENV PYTHONPATH=/opt/deps

USER nonroot:nonroot

EXPOSE 8000

CMD ["-m", "gunicorn", "app:app", "--bind", "0.0.0.0:8000"]

pip install --target=/opt/deps lays packages flat on disk — copyable, no symlinks. That beats the common COPY --from=builder /opt/venv trick: a venv’s bin/python is a symlink to the builder’s interpreter path (/usr/local/bin/python3.x), which doesn’t exist inside distroless, so the copied venv won’t start. One caveat: distroless/python3 is still experimental and pins a specific interpreter version — match the builder’s python:3.11-slim to it, or fall back to python:3.12-slim as the runtime and keep the same --target pattern.

Go multi-stage with scratch

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

WORKDIR /build

COPY go.mod go.sum ./
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server .

# Stage 2: Runtime (scratch = empty image)
FROM scratch AS runtime

COPY --from=builder /build/server /server
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

EXPOSE 8080

ENTRYPOINT ["/server"]

scratch is a zero-byte image — the only thing in your container is your binary. CGO_ENABLED=0 is mandatory (no libc to link against), and the CA bundle has to come along because scratch ships nothing, including certificates. If that sounds like assembling the OS by hand — because it is — static-debian12 is scratch plus the few files any real app needs (certs, tzdata, a nonroot passwd entry), which is why most teams land there instead.

Java multi-stage with Gradle

# Stage 1: Build
FROM gradle:8.7-jdk21-alpine AS builder

WORKDIR /build

COPY build.gradle settings.gradle ./
COPY src ./src

RUN gradle bootJar --no-daemon

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

WORKDIR /app

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

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

EXPOSE 8080

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

JRE Alpine carries no convenience user — USER temurin looks plausible and fails at runtime (“unable to find user”). Create the account first — or leave USER out entirely. And use ENTRYPOINT exec form here: the jar path inside CMD would work, but ENTRYPOINT signals the container is the JVM process, which makes signals like SIGTERM reach Java correctly for graceful shutdown.

.dockerignore for a smaller context

# .dockerignore
node_modules
dist
.git
.gitignore
.env
.env.local
*.md
.vscode
.idea
coverage
.nyc_output
docker-compose*.yml

The context is what gets uploaded to the daemon before a single layer runs — on a repo with node_modules/ and .git that’s routinely hundreds of MB per build. It also protects cache: a stray change in an ignored file no longer invalidates COPY . ..

Layer-order optimization

FROM node:20-alpine AS builder

WORKDIR /app

# Copy dependency files first (cached unless package.json changes)
COPY package*.json ./
RUN npm ci

# Copy source (invalidates cache only when source changes)
COPY . .

RUN npm run build

Docker caches per layer and throws the cache away at the first instruction that changed — everything after it rebuilds. Dependencies change weekly; source changes hourly. Putting the expensive npm ci above the cheap COPY . . means a code commit reuses the dependency layer instead of reinstalling the world.

Explanation

Every FROM starts a clean image, and COPY --from=<stage> is the only way files cross over. Whatever a stage doesn’t export disappears with it — the SDK, the caches, the intermediate objects. The last stage alone becomes the tagged image.

flowchart diagram: subgraph Builder[

Worth internalizing:

  • Named stages (AS builder, AS runtime) are names that both COPY --from=builder and docker build --target test resolve against.
  • .dockerignore is context, not image — it speeds uploads and shields cache, but it doesn’t shrink the image itself.
  • npm ci over npm install — ci installs exactly the lockfile and fails if it’s out of sync; install can rewrite it, which means two builds from the same commit can produce different trees.
  • Non-root user — USER node/nonroot/appuser before ENTRYPOINT; every runtime needs it, most don’t provide it.
  • Strip symbols — -ldflags="-s -w" on Go removes DWARF/symbol tables (~30% of the binary) that nothing in production reads.

Variants

Rust multi-stage build

# Stage 1: Build
FROM rust:1.78 AS builder

WORKDIR /build

COPY Cargo.toml Cargo.lock ./
COPY src ./src

RUN cargo build --release

# Stage 2: Runtime
FROM debian:bookworm-slim AS runtime

RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates libssl3 && \
    rm -rf /var/lib/apt/lists/*

COPY --from=builder /build/target/release/myapp /usr/local/bin/myapp

USER nobody

EXPOSE 8080

CMD ["myapp"]

Rust links glibc dynamically by default, so bookworm-slim (~80MB) is the pragmatic floor — or build with RUSTFLAGS="-C target-feature=+crt-static" and land on scratch/distroless like the Go example.

BuildKit cache mounts

# syntax=docker/dockerfile:1.7

FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
# Mount npm cache as a volume (persists across builds)
RUN --mount=type=cache,target=/root/.npm npm ci

COPY . .
RUN --mount=type=cache,target=/root/.npm npm run build
# Python pip cache mount
FROM python:3.12-slim AS builder

WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
# Go module cache mount
FROM golang:1.22-alpine AS builder

WORKDIR /build

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 go build -ldflags="-s -w" -o server .

Cache mounts persist package-manager caches on the builder across builds without baking them into any layer — dependency downloads drop to near-zero on rebuilds. For rebuild speed in CI nothing else comes close, though it does require the # syntax=docker/dockerfile:1.7 header and BuildKit — already the default builder in current Docker.

Test stage for CI

# Stage 1: Dependencies
FROM node:20-alpine AS deps

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

# Stage 2: Test
FROM deps AS test
COPY . .
RUN npm run lint
RUN npm run test:unit

# Stage 3: Build
FROM deps AS builder
COPY . .
RUN npm run build

# Stage 4: Production
FROM node:20-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"]
# Run tests only
docker build --target test .

# Build production image (skips test stage if already cached)
docker build --target production -t myapp:latest .

Because stages only resolve what their FROM chain references, test and deps cost build time but zero image bytes — and --target test gives you a CI job without publishing anything.

Image size analysis

# Check image size
docker images myapp:latest
# REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
# myapp        latest    abc123         2 minutes ago   148MB

# Analyze layer sizes
docker history myapp:latest --no-trunc --format "{{.Size}}\t{{.CreatedBy}}"

# Compare before/after
docker images --format "{{.Repository}}:{{.Tag}}\t{{.Size}}" | grep myapp
# Use dive for detailed layer analysis
dive myapp:latest
# Shows each layer, what was added/removed, and potential waste

docker history is where surprise layers surface — a stray RUN apt-get update that cached 40MB of indexes, or a debug package installed “temporarily” three months ago. dive goes interactive and lets you diff what each layer actually added.

Multi-architecture builds

# Dockerfile (same for all platforms)
FROM --platform=$BUILDPLATFORM node:20-alpine AS builder

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

COPY . .
RUN npm run build

FROM --platform=$TARGETPLATFORM node:20-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"]
# Build for amd64 and arm64
docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t myapp:latest \
  --push .

$BUILDPLATFORM runs the compile stage on your host’s arch (fast, native) while $TARGETPLATFORM produces per-arch final images — QEMU only emulates the cheap packaging steps, not the compiler.

Best Practices

  • Multi-stage for anything beyond a script — compilers and package managers never belong in prod.
  • Smallest base that works: scratch > distroless > alpine > slim > full, in that order.
  • Dependency files before source — COPY package*.json ./ above COPY . . keeps the expensive layer cached.
  • npm ci, never npm install, in Dockerfiles — reproducible trees or a loud failure.
  • --omit=dev (npm) / --no-dev (pip) so devDependencies don’t leak across stages.
  • .dockerignore from day one — context bloat is invisible until builds crawl.
  • Non-root USER before ENTRYPOINT — create the user if the runtime doesn’t ship one.
  • -ldflags="-s -w" on Go — free ~30% by dropping debug info nobody reads.
  • Chain package-manager cleanup into the same RUN (apt-get install … && rm -rf /var/lib/apt/lists/*) — each RUN is a layer, and deleted files still weigh bytes in earlier layers.
  • Tag real versions — :latest pins nothing and breaks rollbacks.

Common Mistakes

  • No .dockerignore — node_modules and .git ride to the daemon on every build.
  • COPY . . above dependency install — every commit flushes the dependency cache.
  • npm install in CI — lockfile drift means the tested image isn’t the shipped one.
  • Shipping the SDK — compilers stay in the builder stage; that’s what COPY --from is for.
  • Running as root — especially pointless on minimal bases where the fix is two lines.
  • Deleting files in a later RUN — layers are additive; rm doesn’t shrink what a previous layer already weighs.
  • USER pointing at an account nobody created (temurin, app) — add it first or the container refuses to start.
  • Assuming --target is just for tests — it’s also how you ship debug and release variants from one Dockerfile.

Further Reading

See Also

Frequently Asked Questions

How much can multi-stage builds reduce image size?

Typically 80-90 percent on language runtimes: Node.js apps drop from ~900MB to ~150MB, a Go service from ~1.2GB to ~15MB on scratch. Measure yours with docker images --format "{{.Size}}" — the win depends on how much toolchain was leaking into production.

Can I skip stages during build?

Yes — docker build --target builder stops at that stage and ignores the rest. You get a test image or a debuggable builder without ever producing the production one.

How do I debug a distroless or scratch image?

No shell exists inside, so docker exec -it sh is off the table. Options: build a :debug variant (distroless publishes one with busybox), docker cp tools into the running container, or attach an ephemeral debug container in Kubernetes. For more, see distroless multi-stage builds.

Should I use Alpine or slim?

Alpine is smaller (~5MB) but runs musl libc — Python C extensions and Node native addons occasionally break on it. Slim is glibc-compatible at ~80MB. Start with Alpine and switch to slim if a native dependency refuses to build on musl.

Do cache mounts work without BuildKit?

No — --mount=type=cache needs BuildKit and the # syntax=docker/dockerfile:1.7 header. BuildKit is the default builder in current Docker Engine and Docker Desktop, so for most setups it just works.