本文由 AI 分析生成
建立時間: 2026-03-28 來源: https://blog.alexellis.io/mutli-stage-docker-builds/
Summary
Alex Ellis’s 2017 post documenting Docker’s multi-stage build feature (then newly merged as a PR) as a replacement for the manual “builder pattern.” Multi-stage builds collapse what previously required two Dockerfiles and a shell orchestration script into a single Dockerfile, producing the same tiny output image (10MB vs 672MB for a Go binary) with far less maintenance overhead.
介紹 Docker 多階段建置如何取代繁瑣的 builder pattern:原需兩個 Dockerfile 加一個 shell 腳本,現在單一 Dockerfile 即可完成,Go binary 映像從 672MB 縮至 10MB。
Key Points
- The old builder pattern: 2 Dockerfiles + shell script — Dockerfile.build (from golang SDK), Dockerfile (from alpine), build.sh (docker create/cp/rm orchestration)
- Multi-stage syntax: multiple
FROMstatements in one Dockerfile;COPY --from=<stage>copies artifacts between stages; lastFROMis the final image - Named stages:
FROM golang:1.7.3 as builderthenCOPY --from=builder ...— more readable than--from=0numeric index - Size result: 10.3MB (multi-stage alpine image) vs 672MB (golang base image)
- Historical note: this was a bleeding-edge PR at time of writing (March 2017); now standard Docker practice for all compiled languages
Insights
Multi-stage builds solved a real operational problem: the builder pattern required teams to maintain synchronization between two Dockerfiles and a script, which routinely drifted. A single Dockerfile is the single source of truth for how an image is built.
The pattern extends beyond Go to any compiled language (Rust, C++, Java, TypeScript) or any case where build tooling shouldn’t be in the production image. The general form is: “fat image to build, minimal image to run.”
The COPY --from=<stage> mechanism is surprisingly powerful: you can copy from named stages, from numeric stage indices, or even from external images (COPY --from=nginx:latest /etc/nginx ...), enabling base image pinning without rebuilding.
Connections
Raw Excerpt
Multi-stage builds give the benefits of the builder pattern without the hassle of maintaining three separate files. This is huge for developers and maintainers, especially when you support multiple Dockerfiles for different architectures.