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
scratchimage - Build Python and Java services with the same pattern
- Use named stages,
--targetandCOPY --froman 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.
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.
FROM node:20-alpine AS builderWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY tsconfig.json ./COPY src/ ./src/RUN npm run build FROM node:20-alpine AS productionWORKDIR /appENV NODE_ENV=productionCOPY package.json package-lock.json ./RUN npm ci --omit=dev && npm cache clean --forceCOPY --from=builder /app/dist ./dist# The official node image already contains an unprivileged user named nodeUSER nodeEXPOSE 8080CMD ["node", "dist/server.js"]# Build the full image and the builder stage separately to comparedocker build -t payment-api:production .docker build --target builder -t payment-api:builder .docker images payment-api# payment-api production ~150MB# payment-api builder ~500MBYour 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.
# syntax=docker/dockerfile:1 FROM golang:1.22-alpine AS builderWORKDIR /srcRUN apk add --no-cache ca-certificatesCOPY go.mod go.sum ./RUN go mod downloadCOPY . .RUN CGO_ENABLED=0 GOOS=linux go build \ -trimpath -ldflags="-s -w" \ -o /out/payment-service ./cmd/payment-service FROM scratch AS productionCOPY --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 userUSER 65532:65532EXPOSE 8080ENTRYPOINT ["/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.
# syntax=docker/dockerfile:1 FROM python:3.12 AS builderWORKDIR /appRUN python -m venv /opt/venvENV PATH="/opt/venv/bin:$PATH"COPY requirements.txt ./RUN pip install --no-cache-dir -r requirements.txt FROM python:3.12-slim AS productionWORKDIR /appCOPY --from=builder /opt/venv /opt/venvENV PATH="/opt/venv/bin:$PATH" \ PYTHONUNBUFFERED=1COPY . .RUN useradd --system --no-create-home --shell /usr/sbin/nologin appuserUSER appuserEXPOSE 8000CMD ["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.
# syntax=docker/dockerfile:1 FROM maven:3.9-eclipse-temurin-21 AS builderWORKDIR /appCOPY pom.xml ./RUN --mount=type=cache,target=/root/.m2 mvn -B dependency:go-offlineCOPY src/ ./src/RUN --mount=type=cache,target=/root/.m2 mvn -B package -DskipTests FROM eclipse-temurin:21-jre AS productionWORKDIR /appCOPY --from=builder /app/target/payment-service.jar app.jarRUN useradd --system --no-create-home --shell /usr/sbin/nologin javauserUSER javauserEXPOSE 8080ENTRYPOINT ["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.
# syntax=docker/dockerfile:1 FROM node:20-alpine AS baseWORKDIR /appCOPY package.json package-lock.json ./ FROM base AS deps-devRUN npm ci FROM deps-dev AS developmentCOPY . .CMD ["npm", "run", "dev"] FROM deps-dev AS testCOPY . .RUN npm test FROM deps-dev AS builderCOPY . .RUN npm run build FROM base AS productionENV NODE_ENV=productionRUN npm ci --omit=devCOPY --from=builder /app/dist ./distUSER nodeCMD ["node", "dist/server.js"]# 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 imagedocker build --target production -t payment-api:prod . # Local development imagedocker 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.
FROM alpine:3.20COPY --from=busybox:1.36 /bin/busybox /usr/local/bin/busyboxCOPY --from=ghcr.io/astral-sh/uv:0.4 /uv /usr/local/bin/uvCMD ["sh"]Pin the source image to a specific tag or digest, because you are trusting its contents.
Production Best Practices & Common Pitfalls
- Name every stage.
AS builderis far clearer than--from=0. - Copy specific paths. Copying whole directories drags source code and secrets into the final image.
- Order layers by change frequency. Copy dependency manifests and install first, then copy source, so edits do not invalidate the dependency layer.
- Run as non-root in the final stage. Use a numeric UID for
scratchand distroless images. - Run tests in a stage. A
testtarget makes CI a singledocker build --target test. - Keep secrets out of every stage. Build arguments and copied files are visible in image history. Use
RUN --mount=type=secretfor tokens.
Common MistakeCopying
node_modulesfrom the builder and also runningnpm ci --omit=devin production. Pick one approach. Copying brings dev dependencies along, reinstalling produces a clean production tree.
SecurityA
scratchor 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.
TipBuild only the builder stage with
docker build --target builder -t myapp:debug .and open a shell in it to see exactly what was produced.
RememberOnly 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 |