Skip to main content

Building Multi-Stage Docker Images

Write multi-stage Dockerfiles for Node.js, Go, Python and Java that ship only runtime files, cutting image size and attack surface.

44 Terms

Overview and What You Will Learn

A multi-stage build is a Dockerfile with more than one FROM instruction, where each FROM starts a new stage and only the final stage becomes the image you ship. You compile and test in a heavy stage full of tools, then copy just the finished output into a small runtime stage. The compilers, package caches and test frameworks never reach production.

In this lab you will:

  • Convert a single-stage Node.js image into a multi-stage build and measure the difference
  • Build a Go service into a scratch image
  • Build Python and Java services with the same pattern
  • Use named stages, --target and COPY --from an external image

Why This Matters in Production

Image size is a reliability metric. When an autoscaler adds nodes during a traffic spike, each new node must pull your image before serving a single request, so a 1 GB image delays capacity far longer than a 100 MB one. Streaming platforms such as Hotstar scale out aggressively during live events, which is why small images and fast pulls matter. Smaller images also contain fewer packages, so scanners report fewer CVEs.

Core Principles

Each FROM begins an isolated filesystem. You name a stage with AS and pull files out of it with COPY --from=<stage>. Anything you do not copy is discarded.

flowchart TD A[Source code] --> B[Stage 1: builder
compilers and dev tools] B -->|COPY --from| C[Compiled output] C --> D([Stage 2: production
runtime only]) B -.->|discarded| E[Build tools and caches] classDef build fill:#FFEDD5,color:#1E293B classDef ship fill:#10B981,color:#FFFFFF classDef trash fill:#FEE2E2,color:#1E293B class A,B build class C,D ship class E trash

Two rules make multi-stage builds work well. First, the final stage should start from the smallest base that can run your app. Second, copy specific paths, never COPY --from=builder /app ., so you control exactly what ships.

Detailed Step-by-Step Practical Lab

Milestone 1: Node.js with TypeScript

Compile TypeScript in the builder, then run plain JavaScript on a slim runtime with production dependencies only.

Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src/ ./src/
RUN npm run build
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=builder /app/dist ./dist
# The official node image already contains an unprivileged user named node
USER node
EXPOSE 8080
CMD ["node", "dist/server.js"]
Bash
# Build the full image and the builder stage separately to compare
docker build -t payment-api:production .
docker build --target builder -t payment-api:builder .
docker images payment-api
# payment-api production ~150MB
# payment-api builder ~500MB

Your exact sizes depend on your dependencies, but the builder stage is always the larger one.

Milestone 2: Go into a scratch Image

Go compiles to a static binary, so the runtime image can contain nothing but that binary. This gives the smallest possible image and almost no attack surface.

Dockerfile
# syntax=docker/dockerfile:1
FROM golang:1.22-alpine AS builder
WORKDIR /src
RUN apk add --no-cache ca-certificates
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build \
-trimpath -ldflags="-s -w" \
-o /out/payment-service ./cmd/payment-service
FROM scratch AS production
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /out/payment-service /payment-service
# scratch has no /etc/passwd, so use a numeric user
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/payment-service"]

CGO_ENABLED=0 produces a statically linked binary. Without it the binary expects glibc and fails to start in scratch with a confusing "not found" error. If you want a shell-free image with certificates, a user and timezone data already included, use gcr.io/distroless/static-debian12:nonroot instead of scratch.

Milestone 3: Python with a Virtual Environment

Install dependencies into a virtual environment in the builder, then copy the whole environment into the runtime. A venv at a neutral path like /opt/venv is readable by any user, unlike /root/.local.

Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.12 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
FROM python:3.12-slim AS production
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH" \
PYTHONUNBUFFERED=1
COPY . .
RUN useradd --system --no-create-home --shell /usr/sbin/nologin appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

If a package needs a C library at runtime (for example libpq5 for PostgreSQL drivers), install the runtime library in the final stage. Only the headers and compilers belong in the builder.

Milestone 4: Java with Maven

Build the jar with a full JDK and Maven, then run it on a JRE-only image.

Dockerfile
# syntax=docker/dockerfile:1
FROM maven:3.9-eclipse-temurin-21 AS builder
WORKDIR /app
COPY pom.xml ./
RUN --mount=type=cache,target=/root/.m2 mvn -B dependency:go-offline
COPY src/ ./src/
RUN --mount=type=cache,target=/root/.m2 mvn -B package -DskipTests
FROM eclipse-temurin:21-jre AS production
WORKDIR /app
COPY --from=builder /app/target/payment-service.jar app.jar
RUN useradd --system --no-create-home --shell /usr/sbin/nologin javauser
USER javauser
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

For Spring Boot, the layered jar mode (-Djarmode=tools in current releases) splits dependencies from your code so Docker caches the large dependency layer between builds. Check the Spring Boot documentation for the exact flags in your version.

Milestone 5: Name Stages for Dev, Test and Production

One Dockerfile can serve every environment. Use --target to build just the stage you need, which also lets BuildKit skip stages the target does not depend on.

Dockerfile
# syntax=docker/dockerfile:1
FROM node:20-alpine AS base
WORKDIR /app
COPY package.json package-lock.json ./
FROM base AS deps-dev
RUN npm ci
FROM deps-dev AS development
COPY . .
CMD ["npm", "run", "dev"]
FROM deps-dev AS test
COPY . .
RUN npm test
FROM deps-dev AS builder
COPY . .
RUN npm run build
FROM base AS production
ENV NODE_ENV=production
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
USER node
CMD ["node", "dist/server.js"]
Bash
# Run tests in CI by building the test stage (a failing test fails the build)
docker build --target test -t payment-api:test .
# Build the shippable image
docker build --target production -t payment-api:prod .
# Local development image
docker build --target development -t payment-api:dev .
Milestone 6: Copy Tools from Another Image

COPY --from accepts any image reference, not just stages from the same file. This pulls a single binary into a minimal image without installing a package manager.

Dockerfile
FROM alpine:3.20
COPY --from=busybox:1.36 /bin/busybox /usr/local/bin/busybox
COPY --from=ghcr.io/astral-sh/uv:0.4 /uv /usr/local/bin/uv
CMD ["sh"]

Pin the source image to a specific tag or digest, because you are trusting its contents.

Production Best Practices & Common Pitfalls

  1. Name every stage. AS builder is far clearer than --from=0.
  2. Copy specific paths. Copying whole directories drags source code and secrets into the final image.
  3. Order layers by change frequency. Copy dependency manifests and install first, then copy source, so edits do not invalidate the dependency layer.
  4. Run as non-root in the final stage. Use a numeric UID for scratch and distroless images.
  5. Run tests in a stage. A test target makes CI a single docker build --target test.
  6. Keep secrets out of every stage. Build arguments and copied files are visible in image history. Use RUN --mount=type=secret for tokens.
Common Mistake

Copying node_modules from the builder and also running npm ci --omit=dev in production. Pick one approach. Copying brings dev dependencies along, reinstalling produces a clean production tree.

Security

A scratch or distroless final stage removes shells and package managers, so an attacker who gets code execution has far fewer tools to work with. It also makes vulnerability scans much shorter.

Tip

Build only the builder stage with docker build --target builder -t myapp:debug . and open a shell in it to see exactly what was produced.

Remember

Only the last stage (or the one named by --target) becomes the image. Earlier stages are build-time scaffolding.

Quick Reference & Troubleshooting Commands

Command Description
docker build --target STAGE -t IMG . Build up to a named stage
docker history IMG Show size added by each layer
docker images IMG Compare image sizes
docker build --no-cache . Rebuild without layer cache
Symptom Likely cause and fix
stage not found Typo in --from, match the AS name exactly
exec format error Wrong CPU architecture, build with --platform linux/amd64
not found when starting a Go binary Dynamically linked, set CGO_ENABLED=0
TLS errors in scratch Missing CA bundle, copy ca-certificates.crt
permission denied on copied files Files owned by root, use COPY --chown= or fix the venv path
Rebuilds are slow COPY . . before dependency install, move it after

Resources

Explore More in Docker Images and Registry Management

All 4 Topics

Frequently Asked Questions

Is Building Multi-Stage Docker Images free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Building Multi-Stage Docker Images topic cover?

Write multi-stage Dockerfiles for Node.js, Go, Python and Java that ship only runtime files, cutting image size and attack surface.

Found a mistake, an outdated step or a broken link?