Docker Multi-Stage Builds: A Practical Guide with Compose Examples
Table of content
A Docker multi stage build uses multiple FROM statements in a single Dockerfile so you can compile your application in a tool-heavy builder environment and copy only the finished artifacts into a slim runtime image. By leaving compilers, SDKs, and intermediate build files behind in earlier stages, you shrink the final container image and remove unnecessary debugging tools from production.
This guide is for software developers, DevOps engineers, and technical leads who want to cut container bloat and speed up CI/CD pipelines. You will learn how to structure multi-stage Dockerfiles, target specific stages in local development with Docker Compose, avoid variable scoping and security traps, and use BuildKit for parallel execution and cross-compilation.
What is a Docker multi-stage build and how does it work?
A Docker multi-stage build uses multiple FROM instructions in a single Dockerfile so you can compile your application in a tool-heavy environment and copy only the finished artifacts into a minimal runtime image. Each FROM line begins a fresh build stage that can pull a completely different base image, allowing you to pair a full SDK image for compilation with a minimal OS layer for deployment.
Docker introduced multi-stage build support, target stage selection, and ARG support inside FROM instructions in Docker Engine 17.05.0-ce on May 4, 2017. Before that release, teams looking into how Docker containerization works had to choose between shipping bloated single-stage images or maintaining separate build and runtime Dockerfiles glued together by shell scripts. With the official Docker multi-stage builds workflow, a single file defines the entire pipeline.
When you want to reduce Docker image size, multi-stage patterns provide immediate, measurable savings. In Docker’s own multi-stage builds guide, turning a single-stage Node.js Dockerfile into a three-stage one shrinks the image from 1.87 GB to about 400 MB, and most of the saving comes from moving to a slim runtime base image. That reduction also improves container security by stripping development and debugging tools out of the deployed image.
| Criterion | Multi-stage build (BuildKit) | Single-stage build | Multi-stage build (Legacy Engine builder) |
|---|---|---|---|
| Final production image size (Spring Boot benchmark) | 428 MB | 880 MB | 428 MB |
| Compilers and SDKs in production image | Left behind in earlier stages | Saved in final image | Left behind in earlier stages |
| Execution of independent build stages | Executed in parallel | Sequential in one stage | Sequential |
| Behavior when building with –target | Skips unneeded stages; builds only dependencies | Not applicable (single stage) | Processes all stages leading up to the target |
| Maintenance overhead | Single Dockerfile for build and runtime | Single Dockerfile | Single Dockerfile for build and runtime |
| Default SBOM scan coverage (–sbom=true) | Final stage only (unless stage scan ARG is set) | Entire single stage | Not supported by legacy builder |
How to write a multi-stage Dockerfile step by step
You write a multi-stage Dockerfile by naming each stage with the AS keyword on its FROM line and pulling compiled files across stages using COPY --from. By default, Docker does not name build stages and references them by their integer index starting at 0 for the first FROM instruction, such as COPY --from=0. Naming a stage by appending AS <NAME> (for example, FROM golang:1.26 AS build) and referencing COPY --from=<NAME> is much safer because it prevents your COPY commands from breaking if you reorder stages later.
Follow these steps to construct a multi-stage Dockerfile:
- Declare the initial builder stage using
FROM <base_image> AS <stage_name>with an image that includes your compiler or SDK. - Copy your source files into the builder stage and run the compilation command.
- Declare a new runtime stage using a second
FROMinstruction with a minimal base image. - Use the dockerfile copy –from instruction (
COPY --from=<stage_name>) to transfer only the compiled binary or bundle from the builder stage into the runtime stage. - Define the
ENTRYPOINTorCMDinstruction to run the application in the final stage.
Here is a Docker multi stage build example that uses Go and a scratch base, where a Go binary is compiled in a full SDK environment and copied into an empty scratch image:
# Stage 0: Compile the Go binary
FROM golang:1.26 AS build
WORKDIR /src
COPY main.go .
RUN CGO_ENABLED=0 go build -o /bin/app main.go
# Stage 1: Minimal runtime stage
FROM scratch
COPY --from=build /bin/app /app
ENTRYPOINT ["/app"]
You can also chain stages together or pull files from outside your Dockerfile. A new build stage can pick up where an earlier stage left off by referencing the earlier stage’s name in its FROM directive, such as FROM builder AS build1. This lets you build a shared base stage once and reuse it across multiple derivative stages. COPY --from is not restricted to stages defined in the same Dockerfile; it can copy files directly from an external image stored locally or in a Docker registry, such as COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf.
For interpreted or bundled runtimes, a Node.js production workflow combined with an external configuration pull looks like this:
# Base stage for shared dependencies
FROM node:lts-alpine AS base
WORKDIR /app
COPY package*.json ./
# Builder stage picking up from base
FROM base AS builder
RUN npm ci
COPY . .
RUN npm run build
# Production stage copying from builder and an external image
FROM node:lts-alpine AS prod
WORKDIR /app
COPY --from=nginx:latest /etc/nginx/nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /app/dist ./dist
CMD ["node", "dist/main.js"]
Stopping at a specific target stage and how BuildKit executes it
While Docker builds the final stage of a Dockerfile by default, passing the --target flag lets you stop at any named stage, and BuildKit optimizes this by skipping unneeded stages and running independent ones in parallel. If you run a standard build without specifying a target, Docker automatically processes up to the last stage defined in the file.
When you need to run a docker build target stage command for debugging, executing unit test stages, or separating debug and production environments, pass --target <stage_name> to docker build:
docker build --target build -t hello .
How Docker executes that command depends on the builder engine. BuildKit on GitHub, the concurrent, cache-efficient builder toolkit maintained under the Moby project and distributed under the Apache-2.0 license, handles stage dependency graphs differently than the legacy Docker Engine builder. The legacy builder processes every stage leading up to your selected --target in top-to-bottom order, even if the target stage has no dependency on them. BuildKit analyzes the dependency graph, skips unneeded stages completely, and builds only the stages that your target stage actually depends on.
Splitting instructions into separate stages also enables docker buildkit multi stage parallel execution. If your final stage copies frontend assets from a Node stage and backend binaries from a Go stage, BuildKit runs both compilation stages concurrently to cut total build time.
Docker Compose tutorial: targeting stages for local development and production
In a compose.yaml file, the build.target attribute tells Docker Compose which specific stage of a multi-stage Dockerfile to build for a service. This Docker Compose tutorial section shows how to pair a single Dockerfile with Compose so your local environment runs hot-reloading development tools while production runs a locked-down artifact.
According to the Docker Compose Build Specification, setting target: prod or target: dev under a service’s build key directs Compose to stop at that stage. In Docker Compose, multiple services in the same Compose application can share base layers and system packages by placing the shared declarations into a base stage inside a single multi-stage Dockerfile and having each service point to its respective stage via the target setting in its build section.
Developers can also combine multi-stage builds (using separate development and production stages) with Docker Compose Watch by configuring the develop.watch subsection in compose.yaml (using actions such as sync, rebuild, or restart in Compose 2.32.0+) to update running development containers automatically whenever local source code changes.
services:
api-dev:
build:
context: .
target: builder
develop:
watch:
- action: sync
path: ./src
target: /app/src
- action: rebuild
path: package.json
worker-prod:
build:
context: .
target: prod
Watch out for a common migration issue when moving to Docker Compose v2. In legacy Compose v1, images built sequentially, so teams often reused one service’s built image as the FROM base image inside another service’s Dockerfile without declaring the relationship. Because Compose v2 uses BuildKit to build service images in parallel, reusing another service’s image as a base requires declaring that dependent base image as an additional build context (or consolidating them into shared stages of a multi-stage Dockerfile) so BuildKit orders the builds properly.
Common pitfalls: ARG scoping, secret leaks, and SBOM gaps
The most common mistakes in multi-stage builds involve losing global ARG values across stage boundaries, leaking credentials in image layers via ENV or ARG, and generating incomplete Software Bills of Materials (SBOMs). Applying multi-stage build best practices requires explicit control over how variables, secrets, and metadata cross stage boundaries.
Understanding ARG scope in multi-stage builds prevents silent build failures. Build arguments (ARG) declared in the global scope before the first FROM instruction are available inside FROM lines, but they are not automatically inherited into the body of build stages. To read a global ARG inside a stage, you must explicitly re-declare ARG <name> without a value inside that stage. Once an ARG or ENV variable is declared or consumed inside a specific stage, any child stage that inherits from it via FROM <parent_stage> inherits the variable automatically, whereas unrelated stages starting from a fresh base image do not.
ARG GO_VERSION=1.26
ARG APP_ENV=production
FROM golang:${GO_VERSION} AS parent
# Re-declare global ARG to bring it into this stage's scope
ARG APP_ENV
ENV CONFIG_MODE=${APP_ENV}
FROM parent AS child
# Inherits APP_ENV and CONFIG_MODE automatically from parent
RUN echo "Mode is $CONFIG_MODE"
FROM alpine:latest AS unrelated
# Does NOT inherit APP_ENV from parent; must re-declare to consume global value
ARG APP_ENV
RUN echo "Mode in unrelated stage is $APP_ENV"
A second mistake is assuming that secrets used only in an early builder stage are safe if passed via ARG or ENV. Passing sensitive data through ARG or ENV is a security hazard because those values persist in image metadata, provenance attestations, and image history. Instead, use secret mounts (RUN --mount=type=secret) or SSH mounts (RUN --mount=type=ssh), which mount sensitive data temporarily (under /run/secrets/<id> by default) during a single instruction without persisting it in the final image or metadata.
FROM golang:1.26 AS build
WORKDIR /src
COPY . .
RUN --mount=type=secret,id=netrc,target=/root/.netrc \
go mod download && go build -o /app
A third issue affects compliance and vulnerability scanning. When you run BuildKit’s SBOM generator (--sbom=true) on a multi-stage build, it scans only the final stage of the image by default, omitting build-time dependencies and compilers used in earlier stages. If your compliance policy requires full visibility into build-time dependencies or the build context, declare ARG BUILDKIT_SBOM_SCAN_STAGE=true inside the earlier stages or set ARG BUILDKIT_SBOM_SCAN_CONTEXT=true.
Advanced patterns: exporting binaries, cross-compilation, and cache filtering
Beyond building standard runtime images, multi-stage Dockerfiles can export raw binaries directly to the host filesystem, cross-compile code without emulation overhead, and selectively invalidate build caches per stage.
If you want to use Docker as a hermetic compiler that outputs a binary directly to your host machine rather than producing a container image, copy your compiled artifact into a FROM scratch final stage and run docker build --output=. .:
FROM golang:1.26 AS build
WORKDIR /src
COPY main.go .
RUN go build -o /out/my-binary main.go
FROM scratch AS export-stage
COPY --from=build /out/my-binary /
docker build --output=. .
For multi-platform builds, running heavy compilers through QEMU emulation slows down CI pipelines. BuildKit provides predefined global build arguments (BUILDPLATFORM, BUILDOS, BUILDARCH, TARGETPLATFORM, TARGETOS, and TARGETARCH) so your compile stage can run natively on the builder’s host architecture via FROM --platform=$BUILDPLATFORM while cross-compiling binaries for the target architecture:
FROM --platform=$BUILDPLATFORM golang:1.26 AS build
ARG TARGETOS
ARG TARGETARCH
WORKDIR /src
COPY . .
RUN GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o /app main.go
FROM alpine:latest
COPY --from=build /app /app
ENTRYPOINT ["/app"]
When debugging or pulling fresh external data in one stage of a large Dockerfile, running docker build --no-cache wastes time by rebuilding every dependency stage from scratch. When building with Buildx, passing the --no-cache-filter <stage1,stage2> flag lets you ignore the build cache for one or more specific stages while keeping the cached layers for the rest of the Dockerfile:
docker buildx build --no-cache-filter build -t myapp:latest .
Frequently asked questions
Here are direct answers to common questions about configuring, debugging, and securing multi-stage Docker builds.
Why is my ARG variable empty inside a Docker multi-stage build?
An ARG declared before the first FROM instruction lives in the global scope and is not automatically passed into individual build stages. To use that global value inside a stage, add an ARG <variable_name> instruction inside the stage after its FROM line. Any child stage built FROM that stage will then inherit the variable automatically.
Does Docker BuildKit build unused stages in a multi-stage Dockerfile?
No, BuildKit analyzes the dependency graph of your Dockerfile and builds only the stages that your target stage depends on, skipping any unused stages. It also executes independent stages in parallel. In contrast, the legacy Docker Engine builder processes all stages leading up to the target stage sequentially, even if they are not used.
Can you copy files from an external Docker image using COPY –from?
Yes, the COPY --from instruction can pull files directly from any standalone image stored locally or in a remote Docker registry, not only from stages defined in the same Dockerfile. For example, COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf fetches the configuration file straight from the official Nginx image.
How do you target a specific Dockerfile stage in Docker Compose?
Set the build.target attribute under the service definition in your compose.yaml file, such as target: prod. In Docker Compose you can also point multiple services in the same compose.yaml file at different target stages of a single Dockerfile so they share a common base stage.
How do multi-stage builds improve container security and reduce image size?
Multi-stage builds let you compile code in a full SDK stage and use COPY --from to move only the compiled artifact into a minimal runtime stage, leaving compilers, package managers, and intermediate files behind. In Docker’s getting-started guide, this approach cuts a sample app image from 1.87 GB to about 400 MB while also shrinking the attack surface by leaving compilers, package managers, and debugging tools out of the shipped image.
Making container builds part of your delivery pipeline
Multi-stage Dockerfiles pay off most when they are part of a consistent pipeline: shared base stages, cached CI builds, scanned and signed images, and the same artifact promoted from staging to production. If you want to read more, see our guides to Docker containerization and Kubernetes and Docker for your deployments. For hands-on help, our custom software development services cover containerization and cloud delivery.