Multi-stage build

On this page 7

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.

ElementPurposeExample
Named stageLabels a stage for later referenceFROM node:20 AS deps
Stage copyPulls artifacts from another stageCOPY --from=deps /app/node_modules ./node_modules
External image copyCopies files from any imageCOPY --from=nginx:1.27 /etc/nginx/nginx.conf .
Build targetStops the build at a chosen stagedocker build --target test .
Stage reuseBases one stage on anotherFROM base AS dev
Core building blocks of a multi-stage Dockerfile

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 imageApproximate sizeBest suited for
scratch0 MB, emptyStatic binaries in Go or Rust
Distroless staticAbout 2 MBStatic binaries needing CA certificates
AlpineAbout 3 to 4 MBSmall images that still need a shell
Debian slimAbout 25 to 30 MBApps needing glibc and common libraries
Full language imageSeveral hundred MBBuild stages, not runtime
Common final-stage base images

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.

StrategyFinal image contentsMain drawback
Single-stage buildCompilers, sources and app togetherLarge, larger attack surface
Builder pattern with scriptsOnly the app, via external copyingTwo files and fragile glue scripts
Multi-stage buildOnly artifacts chosen per stageDebugging minimal images is harder
BuildpacksDetected runtime plus appLess control over each layer
Image build strategies side by side

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.

SymptomLikely causeFix
Binary not found at startDynamic linking against missing libcBuild statically or use a glibc base
TLS errors on outbound callsNo CA certificates in final stageCopy certificates or use distroless
Slow rebuilds on every changeSource copied before dependenciesCopy manifests first, then source
Secrets visible in historyCredentials passed as ARGUse secret mounts
Unexpected stage skippedBuildKit prunes unused stagesReference it or build its target
Frequent problems in multi-stage builds

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.