A multi-stage build is a container image build technique in which a single Dockerfile defines several stages, each starting with its own FROM instruction, and later stages copy only selected artifacts from earlier ones. In containers and cloud deployment, it separates the build environment with compilers and package managers from the lean runtime image that actually ships.
Before multi-stage builds, teams maintained separate build and runtime Dockerfiles joined by shell scripts, a pattern often called the builder pattern. Multi-stage syntax moved that workflow into one file, which makes images smaller, more secure and reproducible without extra tooling.
How stages and artifact copying work
Each FROM line starts a new stage with a fresh filesystem, and nothing from earlier stages carries over unless it is explicitly copied. A stage can be named with AS, as in FROM golang:1.22 AS build, and a later stage retrieves files with COPY --from=build /out/app /app. Only the final stage becomes the image, unless a different target is selected.
With BuildKit, the default builder in current Docker releases and the engine behind docker buildx, stages form a dependency graph. The builder skips stages the target does not need and runs independent stages in parallel, which shortens build time for projects that compile a frontend and a backend separately.
The table below lists the instructions and options that matter most in a multi-stage Dockerfile.
| Element | Purpose | Example |
|---|---|---|
| Named stage | Labels a stage for later reference | FROM node:20 AS deps |
| Stage copy | Pulls artifacts from another stage | COPY --from=deps /app/node_modules ./node_modules |
| External image copy | Copies files from any image | COPY --from=nginx:1.27 /etc/nginx/nginx.conf . |
| Build target | Stops the build at a chosen stage | docker build --target test . |
| Stage reuse | Bases one stage on another | FROM base AS dev |
Typical stage layouts and runtime base images
Most multi-stage Dockerfiles follow a build, test, runtime sequence. A dependency stage installs packages, a build stage compiles or bundles the code, an optional test stage runs unit tests, and the final stage starts from a minimal base image and receives only the compiled output and required runtime files.
The choice of final base image drives most of the size and security outcome. The sizes below are approximate compressed values that change between releases.
| Base image | Approximate size | Best suited for |
|---|---|---|
| scratch | 0 MB, empty | Static binaries in Go or Rust |
| Distroless static | About 2 MB | Static binaries needing CA certificates |
| Alpine | About 3 to 4 MB | Small images that still need a shell |
| Debian slim | About 25 to 30 MB | Apps needing glibc and common libraries |
| Full language image | Several hundred MB | Build stages, not runtime |
Images built on scratch or distroless bases contain no shell and no package manager, which removes common attack tools but also makes interactive debugging harder. Alpine uses musl instead of glibc, so some compiled dependencies behave differently or need rebuilding.
Multi-stage builds compared with other image strategies
A multi-stage build is a build-time technique, not a runtime feature: the resulting image is an ordinary Open Container Initiative image that any container runtime, such as containerd or Podman, can run. Its value appears when compared with the alternatives that teams used before or use alongside it.
| Strategy | Final image contents | Main drawback |
|---|---|---|
| Single-stage build | Compilers, sources and app together | Large, larger attack surface |
| Builder pattern with scripts | Only the app, via external copying | Two files and fragile glue scripts |
| Multi-stage build | Only artifacts chosen per stage | Debugging minimal images is harder |
| Buildpacks | Detected runtime plus app | Less control over each layer |
Each stage still produces image layers in the builder cache, but intermediate layers are not pushed to the container registry. Only the layers of the final stage reach Docker Hub or a private registry, which reduces storage, transfer time and pull latency on every node that runs the image.
Writing efficient multi-stage Dockerfiles
Efficiency depends on ordering instructions for cache reuse. Copying dependency manifests such as package.json or go.mod before the source code lets the dependency stage stay cached when only application code changes, which can cut rebuilds from minutes to seconds.
- Name every stage instead of referring to stages by number, because numbers break when stages are inserted.
- Use BuildKit cache mounts, such as
RUN --mount=type=cache, to keep package caches out of image layers. - Pass secrets with `RUN –mount=type=secret`, never as build arguments, which can leak into image metadata.
- Pin base image versions or digests in every stage for reproducible builds.
- Run the final stage as a non-root user set with the USER instruction.
A dedicated debug or test target keeps tooling available without shipping it. Developers can build --target dev locally with a shell and debuggers, while continuous integration builds the default final stage for production.
Common mistakes and how to fix them
Most failures in multi-stage builds come from missing runtime dependencies in the slim final stage, which only show up when the container starts. The table pairs frequent symptoms with their usual cause and fix.
| Symptom | Likely cause | Fix |
|---|---|---|
| Binary not found at start | Dynamic linking against missing libc | Build statically or use a glibc base |
| TLS errors on outbound calls | No CA certificates in final stage | Copy certificates or use distroless |
| Slow rebuilds on every change | Source copied before dependencies | Copy manifests first, then source |
| Secrets visible in history | Credentials passed as ARG | Use secret mounts |
| Unexpected stage skipped | BuildKit prunes unused stages | Reference it or build its target |
The short version
Think of building furniture in a workshop full of saws, glue and sawdust, then delivering only the finished table to the customer. Nobody wants the workshop shipped along with it.
A multi-stage build does this for software containers. One step uses all the heavy tools to build the program, and the last step packs only the finished program into a small box. The result is smaller, faster to ship and safer, because there are fewer extra tools for an attacker to misuse.
Where it makes a difference
A platform team at a logistics company deploys a Go API to a Kubernetes cluster of 40 nodes. Its original single-stage image, based on the full Go toolchain image, weighs about 850 MB and contains compilers, source code and hundreds of system packages that vulnerability scanners flag on every release.
The team rewrites the Dockerfile with three stages: dependencies, a static build with CGO_ENABLED=0, and a final stage on a distroless static base. The new image is about 15 MB, scanner findings drop from dozens to nearly zero, and rolling updates finish noticeably faster because each node pulls a fraction of the data. Developers keep a separate dev target with a shell for troubleshooting.