✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.3.2.2 Multi Stage Reduction

A focused guide to Multi Stage Reduction, connecting core concepts with practical Docker and container operations.

Multi-stage reduction is the size savings achieved by separating an image's build process into distinct stages, keeping build-time tooling entirely out of the final image and copying across only the specific output the application actually needs to run.

The Mechanism Behind the Savings

A multi-stage build performs compilation, bundling, or other build steps in an earlier stage that can be as large as necessary, then copies only the resulting output into a much smaller final stage — the build tooling itself never becomes part of the final image at all.

FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o app .

FROM scratch
COPY --from=build /src/app /app
ENTRYPOINT ["/app"]

The entire Go toolchain used in the build stage — many hundreds of megabytes — never appears in the final image, which contains only the compiled binary.

Quantifying the Reduction

Comparing the size of a single-stage build (where the full toolchain remains present) against the equivalent multi-stage build directly demonstrates the magnitude of this technique's effect.

docker build -f Dockerfile.single-stage -t myapp:single .
docker build -f Dockerfile.multi-stage -t myapp:multi .
docker images myapp

For compiled languages especially, this comparison frequently reveals a reduction from hundreds of megabytes down to single-digit megabytes.

Applying the Same Pattern to Interpreted Languages

Even for interpreted languages without a traditional compilation step, multi-stage builds still provide value by separating dependency installation (which might require build tools for compiled extensions) from the final runtime image.

FROM python:3.12 AS build
RUN pip wheel --wheel-dir=/wheels -r requirements.txt

FROM python:3.12-slim
COPY --from=build /wheels /wheels
RUN pip install --no-index --find-links=/wheels -r requirements.txt
Why Multi-Stage Reduction Matters

For applications with any meaningful build step, multi-stage builds typically provide the single largest available size reduction of any individual technique, making this one of the first optimizations worth applying to any Dockerfile that does not already use it.