TL;DR
Master Docker multi-stage builds with this comprehensive guide covering optimization techniques, best practices, and real-world examples for creating efficient container images
Docker Multi-stage Builds: Optimizing Container Images
Executive Summary
A multi-stage build uses several FROM instructions in one Dockerfile. Each stage is a working image; later stages copy selected artifacts out of earlier ones with COPY --from, and only the final stage becomes the shipped image. The effect is decisive: compilers, dependency caches, test frameworks, and source code exist during the build and nowhere in production. This guide covers the basic pattern, worked examples for Node.js, Go, Python, and Java, and the surrounding techniques that make it effective: dependency-first layer ordering, named stages, build targets for CI, external build stages with tests, and BuildKit cache mounts. You should finish able to restructure a single-stage Dockerfile into stages and explain what each stage is for.
Why This Matters
A single-stage build ships everything needed to build the software, not just to run it. That means larger images that pull slowly and cost more to store, a wider vulnerability surface because every build tool is also present at runtime, and a real information leak: source code, build scripts, and sometimes credentials used during the build sit inside the production image where anyone with pull access can extract them. Multi-stage builds remove all three problems with a Dockerfile pattern rather than new tooling, which is why they are considered a baseline practice rather than an optimisation for enthusiasts.
Core Concepts
The Basic Pattern
Name each stage with AS, do the heavy work early, and copy only artifacts forward.
# Stage 1: Build FROM node:16-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build # Stage 2: Runtime FROM node:16-alpine WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/package*.json ./ RUN npm ci --only=production EXPOSE 3000 CMD ["npm", "start"]
Two habits make this work well. Copy dependency manifests and install dependencies before copying source code, so the expensive install layer is cached unless the manifest changes. And keep the runtime stage's base as small as the application allows; the builder can be fat because it is discarded.
Compiled Languages: The Extreme Case
For Go, the build stage needs the full toolchain while the runtime needs almost nothing, because the output is a static binary:
# Stage 1: Build FROM golang:1.20-alpine AS builder WORKDIR /app COPY go.* ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -o server . # Stage 2: Runtime FROM alpine:3.17 RUN apk add --no-cache ca-certificates COPY --from=builder /app/server /server EXPOSE 8080 CMD ["/server"]
The ca-certificates package is the classic gotcha: a minimal runtime image has no CA bundle, so outbound HTTPS calls fail until you add it. The same pattern applies to Rust and to Java when the runtime stage uses a JRE image instead of the full JDK and Maven toolchain:
# Stage 1: Build FROM maven:3.9-eclipse-temurin-17 AS builder WORKDIR /app COPY pom.xml . RUN mvn dependency:go-offline COPY src ./src RUN mvn package -DskipTests # Stage 2: Runtime FROM eclipse-temurin:17-jre-alpine WORKDIR /app COPY --from=builder /app/target/*.jar app.jar EXPOSE 8080 CMD ["java", "-jar", "app.jar"]
Python: Carry the Virtual Environment Forward
Python has no compiled artifact, so the trick is to build a virtual environment in stage one and copy it, intact, into a clean runtime image with the same interpreter version:
# Stage 1: Build FROM python:3.11-slim AS builder WORKDIR /app RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . RUN python setup.py build # Stage 2: Runtime FROM python:3.11-slim COPY --from=builder /opt/venv /opt/venv COPY --from=builder /app/build /app ENV PATH="/opt/venv/bin:$PATH" WORKDIR /app EXPOSE 8000 CMD ["gunicorn", "app:app"]
The interpreter versions in the two stages must match, or the copied environment's paths and binary wheels will not line up.
Testing as a Stage, and Build Targets
Stages can exist purely to be run and discarded. A tester stage lets CI execute the test suite inside the same dependency environment as the build, and docker build --target lets one Dockerfile serve development, test, and production:
# Stage 1: Test FROM node:16-alpine AS tester WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run test # Stage 2: Build FROM node:16-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build # Stage 3: Runtime FROM node:16-alpine WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/package*.json ./ RUN npm ci --only=production EXPOSE 3000 CMD ["npm", "start"]
CI then builds the tester target as a gate and the default final stage for release, with layer caching shared between them.
Multiple Artifacts, One Image
A single Dockerfile can also assemble outputs from independent builders, such as a compiled frontend served next to a backend binary:
# Stage 1: Build Frontend FROM node:16-alpine AS frontend-builder WORKDIR /app COPY frontend/package*.json ./ RUN npm ci COPY frontend . RUN npm run build # Stage 2: Build Backend FROM golang:1.20-alpine AS backend-builder WORKDIR /app COPY backend/go.* ./ RUN go mod download COPY backend . RUN CGO_ENABLED=0 GOOS=linux go build -o server . # Stage 3: Runtime FROM alpine:3.17 RUN apk add --no-cache ca-certificates nginx # Copy frontend assets COPY --from=frontend-builder /app/dist /usr/share/nginx/html # Copy backend binary COPY --from=backend-builder /app/server /server EXPOSE 80 8080 CMD ["sh", "-c", "nginx && /server"]
Whether one combined image is wise depends on scaling: if the frontend and backend need to scale independently, they should ship as separate images from separate final stages instead.
Secrets and Arguments
Build-time secrets must never land in a layer, and that includes ARG values, which are visible in image history. Use BuildKit secret mounts (--mount=type=secret) so credentials are available during a RUN step without being persisted. Ordinary build arguments are fine for configuration that is not sensitive, such as a version string or build flag, provided they are redeclared in each stage that uses them, since arguments do not carry across stages automatically.
CI Integration
In CI, build with BuildKit, push cache to the registry or the CI cache, and scan the final stage's output. The GitHub Actions shape is standard:
# .github/workflows/docker-build.yml
name: Docker Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Build and push
uses: docker/build-push-action@v2
with:
context: .
push: false
tags: myapp:latest
cache-from: type=gha
cache-to: type=gha,mode=maxDecision Framework
| Situation | Recommendation |
|---|---|
| Any compiled or bundled application | Multi-stage; ship the artifact, not the toolchain |
| Interpreted application with heavy dependencies | Build a venv or production-only dependency set in stage one, copy it forward |
| Tests should gate the image | Add a tester stage and build it with --target in CI |
| Frontend and backend deploy together | One Dockerfile, two builder stages, one runtime stage |
| Frontend and backend scale independently | Separate final stages and separate images |
| Build needs a credential | BuildKit secret mount, never ARG or a copied file |
Implementation Checklist
AS and has a single clear job.dockerignore excludes version control data, local dependencies, and environment filesARG or COPY; build secrets use BuildKit mountsTrade-offs
Multi-stage Dockerfiles are longer and harder to read than single-stage ones, and debugging a build means knowing which stage failed and inspecting intermediate stages deliberately. Layer caching across stages can confuse: change an early stage and every dependent copy is rebuilt. Minimal runtime images omit shells and debugging tools, so production troubleshooting leans on logs, metrics, and ephemeral debug containers. For a throwaway script or a prototype that will never be deployed, the structure is overhead without benefit.
When Not to Use
Conclusion
Multi-stage builds separate what software needs to be built from what it needs to run, and ship only the second list. The pattern is mechanical once practised: named stages, dependencies before source, artifacts copied forward, secrets mounted rather than baked. Make it the default shape of every production Dockerfile and image size, scan results, and pull times all improve at once.
References
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.