Multi-Stage Build
A Dockerfile technique that splits compilation (with full SDKs and build tools) from a minimal runtime stage that copies only the final artifacts, drastically shrinking image size and attack surface
Table of Contents
Structure Diagram
What is Multi-Stage Build?
A Dockerfile technique that splits compilation (with full SDKs and build tools) from a minimal runtime stage that copies only the final artifacts, drastically shrinking image size and attack surface. It is a core concept in Containers & Orchestration within Cloud / DevOps.
Core Principles
Multi-Stage Build uses multiple FROM statements in a single Dockerfile: an earlier builder stage installs full compilers, SDKs, and dev dependencies to compile the application, while the final runtime stage starts from a minimal base image and copies only the compiled output via COPY --from=builder.
All intermediate build tools, source code, and caches are discarded from the final image—often shrinking image size by 90%+, accelerating autoscaling image pulls, and eliminating dozens of OS-level CVEs.
Practical Takeaways
- Pair with Distroless or Scratch bases: Static Go/Rust binaries run cleanly on
scratchorgcr.io/distroless/static, removing shells and package managers so attackers have zero living-off-the-land tools. - Run as a non-root user: Switch to
USER nonrootin the final stage to enforce least privilege at runtime. - Exploit BuildKit parallel stages: Independent build stages (e.g., compiling frontend assets and backend binaries) run concurrently under Docker BuildKit.
Notable Examples
- Next.js Standalone Builds: Uses
deps→builder→runnerstages to shrink 1GB+ Node images down to ~120MB. - Go & Rust Microservices: Compiles in a full toolchain image and ships a 15–25MB production image on Distroless.
- Regulated Container Pipelines: Minimizes CVE findings in automated Trivy/Grype registry scans.