本文由 AI 分析生成
建立時間: 2026-03-28 來源: https://alexandre-vazquez.com/multi-stage-dockerfile/
Summary
Alexandre Vazquez’s guide to multi-stage Dockerfiles — using multiple FROM instructions in a single Dockerfile so that build-time artifacts (compilers, build tools, intermediate files) are not included in the final production image. The core mechanism: COPY --from=<stage> selectively copies only needed artifacts between stages.
Alexandre Vazquez 關於多階段 Dockerfile 的指南——在單個 Dockerfile 中使用多個 FROM 指令,使得構建時的工件(編譯器、構建工具、中間文件)不包含在最終生產鏡像中。核心機制:COPY --from=<stage> 在階段之間選擇性地只複製需要的工件。
Key Points
- Problem: single-stage builds include build tools (JDK, npm, compilers) in production images → bloated images with unnecessary attack surface
- Multi-stage mechanism: each
FROMstarts a new stage; name stages withAS <name>; useCOPY --from=<stage>to pull artifacts between stages - Final image only contains what you explicitly copy from previous stages — everything else (build tools, intermediate files) is discarded
- Typical Java pattern:
FROM eclipse-temurin:17-jdk AS builder→ compile;FROM eclipse-temurin:17-jre-alpine→ copy JAR only - Label stages:
LABEL stage=builderconvention for documentation anddocker prune --filter label=stage=builder - Works well with
divefor validating what’s actually in each layer
Insights
Multi-stage builds are the idiomatic solution to the “fat image” problem in modern Dockerfiles. The key benefit is not just image size but attack surface reduction: removing the JDK/compiler from a production JRE image eliminates a whole class of exploitation possibilities. For Go, the benefit is even more dramatic: Go compiles to a static binary that can run in a FROM scratch image with no OS. The pattern also documents the build process better than separate Dockerfiles — the build context is explicit in a single file.
Connections
Raw Excerpt
The main reason the usage of multi-stage build patterns helps reduce the size of the containers is that you can copy any artifact or set of artifacts from one stage to the other. Everything you do not copy is discarded and you are not carrying all these not required components from layer to layer.