Multi-stage Build
Multi-stage build is the Dockerfile pattern that separates build environments from runtime environments. Early stages can compile and test, while the final stage keeps only the runtime artifacts.
βΆArchitecture Diagram
π Data FlowDashed line animations indicate the flow direction of data or requests
A single-stage Dockerfile often leaves compilers, caches, test tools, and package managers inside the final production image. That makes images bigger, slower to move, and harder to secure. Teams need a way to build with heavy tools without shipping them.
Early Docker usage often treated build and runtime as the same container environment. As applications grew, the difference between what is needed to build and what is needed to run became impossible to ignore. Multi-stage build emerged as the declarative answer inside Dockerfile itself.
A builder stage can include SDKs and compilers, produce a binary or `dist/` directory, and then hand only that output to the final stage through `COPY --from`. The final stage can then use a much smaller base image. Stages are both a timeline and a filter for what survives into production.
Multi-stage build and Dockerfile both belong to the same act of describing how an image is built, but multi-stage build is not a tool outside Dockerfile. It is a pattern inside it. It also overlaps with layers in image optimization, yet the question is different: layers control cache reuse within a stage, while multi-stage build decides which outputs survive into the final artifact. If the main pain is rebuild cost inside one stage, layer order is the first thing to inspect. If the pain is build tools and intermediate files leaking into production, multi-stage build is the right lens.
A common frontend pattern builds with Node in an earlier stage and copies only static assets into a lightweight web server image at the end. Backend services see similar benefits when large toolchains can stay in the build stage while the production image keeps only the runtime artifact. The benefit is smaller when the service produces almost no separate build output or when build and runtime environments are already nearly the same, because extra stages then add ceremony more than real reduction.