Multi-Stage Build
A multi-stage build is a Dockerfile pattern with several FROM stages, where earlier stages build the app and the final stage copies in only the output. The final image has no compilers, test tools, or source it does not need.
How it works
Each FROM starts a new stage with its own filesystem. You name stages with AS and copy artifacts between them with COPY --from=<stage>. Only the last stage becomes the final image, and earlier stages are discarded from it, though they stay in the build cache.
Node.js and TypeScript
# syntax=docker/dockerfile:1FROM node:20-alpine AS builderWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY . .RUN npm run build FROM node:20-alpine AS productionWORKDIR /appENV NODE_ENV=productionCOPY package.json package-lock.json ./RUN npm ci --omit=devCOPY --from=builder /app/dist ./distUSER nodeCMD ["node", "dist/server.js"]Go with a static binary
FROM golang:1.23-alpine AS builderWORKDIR /srcCOPY go.mod go.sum ./RUN go mod downloadCOPY . .RUN CGO_ENABLED=0 GOOS=linux go build -o /out/payment-api ./cmd/server FROM gcr.io/distroless/static-debian12:nonrootCOPY --from=builder /out/payment-api /payment-apiENTRYPOINT ["/payment-api"]Python
FROM python:3.12-slim AS builderWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir --prefix=/install -r requirements.txt FROM python:3.12-slimWORKDIR /appCOPY --from=builder /install /usr/localCOPY . .CMD ["python", "app.py"]Useful commands
docker build --target builder -t payment-api:builder . # build one stagedocker run --rm -it payment-api:builder sh # debug inside itYou can also copy from an external image as if it were a stage:
COPY --from=nginx:1.27 /etc/nginx/nginx.conf /tmp/nginx.confTroubleshooting
| Problem | Cause | Fix |
|---|---|---|
| File not found in final stage | Wrong path in COPY --from |
Inspect with --target builder |
| Native module errors on Alpine | musl versus glibc | Use a -slim final base |
| Final image still large | Copying too much | Copy only the output folder |
| Multi-platform build fails | Stage architecture mismatch | Use --platform=$BUILDPLATFORM on builder |
Common Mistake
COPY --from=builder /app .copies source, dev dependencies, and temp files. Copy only the build output.
TipStages do not share environment variables. Redeclare
ARGorENVin each stage that needs them.
Frequently Asked Questions
What does a multi-stage build solve?
Single-stage images keep compilers, caches, and dev dependencies that the running app never needs. Multi-stage builds do the heavy work in one stage and copy only the result into a small final stage, reducing size and attack surface.
What mistake brings the bloat back?
Copying too much from the builder, such as the whole app directory or all node_modules, instead of just the built output and production dependencies.
Can I build or debug a single stage?
Yes. Use docker build --target <stage> to stop at that stage, then run it to inspect files and tools.