# Multi-Stage Build

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

**Field:** Infrastructure  
**Category:** Containers  
**Also known as:** Docker Multi-Stage Build, Multistage Dockerfile, COPY --from

## Think of it like

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

## 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

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.

## 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.

## Why it matters

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

## Common mistake

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

## Three principles

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

## Related terms

- [Dockerfile](https://learn.benibix.com/term/infrastructure/dockerfile)
- [Container Image](https://learn.benibix.com/term/infrastructure/container-image)
- [Base Image](https://learn.benibix.com/term/infrastructure/base-image)
- [Image Layer](https://learn.benibix.com/term/infrastructure/image-layer)
- [.dockerignore](https://learn.benibix.com/term/infrastructure/dockerignore)
- [Build (Software)](https://learn.benibix.com/term/development/build)

![A project folder passes through a .dockerignore filter that drops node_modules and .env. The rest goes into a large build stage holding tools and source code. One arrow carries only the finished app into a small final image.](https://learn.benibix.com/diagrams/inf4-image-builds.svg)

---

Source: https://learn.benibix.com/term/infrastructure/multi-stage-build
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
