Skip to content
BENIBIX Learn

Multi-Stage Build

Infrastructure📦 ContainersImage Builds

Also known as Docker Multi-Stage Build, Multistage Dockerfile, COPY --from

A build in steps. Only the finished app goes into the last image.

Think of it like

Think of it like baking a cake in a messy kitchen. Only the cake goes to the table.

Example

Jack builds a Go program in a stage with all the Go tools. The last stage starts FROM scratch and copies in just the program, so the image holds one file.

Why it matters

Build tools can take hundreds of megabytes. Leaving them out makes images faster to ship and safer to run.

Definition

A multi-stage build is a Dockerfile with more than one FROM line. The first stage holds the tools to build the app, such as a compiler. A later stage starts fresh and copies in only the finished app. Everything left in the first stage is thrown away. The final image is smaller and has fewer tools an attacker could use.

Example code

dockerfile
FROM golang:1.26 AS build
COPY . /src
RUN cd /src && go build -o /bin/app .

FROM scratch
COPY --from=build /bin/app /bin/app
CMD ["/bin/app"]
Two FROM lines make two stages. Only the built program crosses into the final image.
The big build stage is thrown away. Only the finished app is copied into the small final image.

Common mistake

Copying the whole first stage across. Copy only the files the app needs to run.

Key takeaways

  1. 1
    Several FROM lines. Each one starts a new stage.
  2. 2
    Copy what you need. COPY --from takes files across.
  3. 3
    The rest is dropped. Build tools stay out of the final image.