# Multi-stage Docker builds for smaller images

> A multi-stage build uses several FROM lines in one Dockerfile so tools needed to build the app stay out of the final image.

URL: https://levelrail.com/learn/docker/multi-stage-docker-builds/
Updated: 2026-11-27

A multi-stage build uses several `FROM` lines in one [Dockerfile](https://levelrail.com/learn/glossary/#dockerfile)): you build the app in a large stage, then copy only the result into a small final stage. The compiler, package manager and source stay behind, so the image you ship is smaller and has less to patch.

## How it works

A Dockerfile can contain several `FROM` lines. Each `FROM` starts a new stage with its own empty file system and its own base image. Stages do not share anything automatically. The only way to move files between them is `COPY --from=<stage>`, which reaches back into an earlier stage and copies a path into the current one.

The image you get at the end is the last stage (or the one you pick with `--target`). Earlier stages are used only while building, and nothing from them ends up in the final image unless you copied it. That is why the final image can be tiny: it starts from a small base and receives only the output you chose.

Layers and the build cache still work per stage. If you copy `package.json` and run `npm ci` before copying the rest of the source, Docker reuses the dependency layer until the package files change. A stage that nothing else depends on is not built at all when you build a different target (with BuildKit, the default builder in current Docker).

This example builds a static site with Node and serves it with nginx. The same pattern works for Go, Rust and other compiled languages.

## Step 1: Write the Dockerfile

```dockerfile
FROM node:22 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:stable-alpine
COPY --from=build /app/dist /usr/share/nginx/html
```

The first stage is named `build` with `AS build`. The second stage starts from a fresh, small image and takes only the `dist` folder from the first with `COPY --from=build`. Everything else in the first stage is discarded. Adjust `dist` to the folder your build writes. `npm ci` installs exactly what the lock file says, which gives repeatable builds.

Add a `.dockerignore` file next to the Dockerfile with at least these lines so `COPY . .` does not drag in your local dependencies or git history:

```text
node_modules
.git
dist
```

## Step 2: Build it

```bash
docker build -t mysite:multi .
```

What you should see: step lines for both stages, then a success message with the image name. The first build downloads base images, so it is slow. A second build with no changes is mostly cached.

## Step 3: Compare sizes

To see the benefit, build the first stage alone:

```bash
docker build --target build -t mysite:build .
docker image ls mysite
```

`--target build` stops after the stage named `build`. What you should see: two rows for `mysite`, tags `build` and `multi`, with a SIZE column.

## Check it worked

The `build` tag should be much larger than `multi`, because it carries Node and `node_modules`. Now run the small one:

```bash
docker run --rm -p 127.0.0.1:8080:80 mysite:multi
```

`--rm` removes the container when you stop it. The `127.0.0.1` prefix keeps the test private to your machine. Open `http://localhost:8080` and you should see your site served by nginx. To prove tools are gone, run `docker run --rm mysite:multi sh -c 'command -v node'` and expect no output.

## Edge cases and gotchas

- **Stage names are case sensitive.** `AS Build` and `--from=build` do not match. If you use a number instead (`--from=0`), inserting a stage earlier shifts the numbers, so prefer names.
- **Glibc versus musl.** Alpine uses musl. A binary built on a Debian-based image can fail on Alpine with a "not found" error even though the file exists, because its loader is missing. Match the bases, or build a static binary (for Go, `CGO_ENABLED=0`).
- **Architecture mismatch.** An image built on an ARM machine (for example Apple silicon) runs as arm64, and a server that is amd64 will refuse or emulate it. Build for the server with `docker build --platform linux/amd64 .` or use `docker buildx`.
- **Secrets can leak through build arguments.** Values passed with `ARG` or `ENV` can appear in `docker history` and the cache, even in a discarded stage if you push that stage. Use BuildKit secret mounts (`RUN --mount=type=secret`) for tokens.
- **Runtime needs are different from build needs.** A Node app that runs a server needs `node_modules` at runtime. In that case copy `node_modules` (production only, after `npm ci --omit=dev`) as well as the built code.
- **Non-root and file ownership.** Files copied with `COPY --from` are owned by root unless you add `--chown=user:group`, which matters if the final stage sets `USER`.
- **The nginx default config is for port 80.** If you change the listening port, change your `-p` mapping too.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `COPY failed: file not found` | The path after `--from=build` is wrong | Check where the build writes, for example with `docker run --rm mysite:build ls /app` |
| `invalid from flag value` | The stage name does not match `AS` | Make the names identical, including case |
| `failed to solve` with an unknown stage | `--target` names a stage that does not exist | Check the `AS` names in the Dockerfile |
| Final image is still huge | The last stage copied too much, or starts from a large base | Copy only the output folder and use a smaller base |
| `exec format error` when starting | Image built for a different CPU architecture | Rebuild with `--platform` matching the server |
| Build is slow every time | Source copied before dependencies install | Copy `package*.json` first, install, then copy the rest |
| Site shows nginx welcome page | Output folder is empty or named differently | Check the build script's output directory |
| `npm ci` fails in the build stage | No lock file was copied into the stage | Copy `package-lock.json` along with `package.json` |
| Build is fast locally but slow in CI | The layer cache is not kept between runs | Cache the build layers in CI, or keep the dependency step early in the file |

## Real-world scenario

Tom has a Vite site. His single-stage Dockerfile starts from `node:22`, builds the site and serves it with a Node static server. The image is large and every Node security notice applies to it. He rewrites it as two stages: Node builds, nginx serves.

```bash
docker build -t site:old -f Dockerfile.old .
docker build -t site:new .
docker image ls site
```

The `new` tag is a fraction of the size of `old`, and the smaller base has fewer packages to patch. His first run of `new` shows the nginx welcome page. The build wrote to `build/`, not `dist/`, so `COPY --from=build /app/dist` copied nothing useful. He checks the stage with `docker run --rm site:build ls /app`, fixes the path and rebuilds. He also reads [write your first Dockerfile](https://levelrail.com/learn/docker/write-your-first-dockerfile/)) for the cache rule and moves `COPY package*.json` above the source copy, so rebuilds reuse the [build cache](https://levelrail.com/learn/glossary/#build-cache)). He runs the result with a loopback-only port, as in [publish container ports safely](https://levelrail.com/learn/docker/publish-container-ports-safely/)).

## Quick reference

| Task | Command or line |
| --- | --- |
| Name a stage | `FROM node:22 AS build` |
| Copy from a stage | `COPY --from=build /app/dist /usr/share/nginx/html` |
| Build up to one stage | `docker build --target build -t app:build .` |
| Compare sizes | `docker image ls app` |
| Build for another CPU | `docker build --platform linux/amd64 .` |
| Inspect a stage's files | `docker run --rm app:build ls /app` |

## Related lessons

- [Write your first Dockerfile](https://levelrail.com/learn/docker/write-your-first-dockerfile/)): the base instructions this builds on
- [Image, container and registry explained](https://levelrail.com/learn/docker/image-container-registry-explained/)): what an image really is
- [Free disk space with docker prune safely](https://levelrail.com/learn/docker/free-disk-space-with-docker-prune-safely/)): clean up the build stages you no longer need
- [Update a container to a new image](https://levelrail.com/learn/docker/update-a-container-to-a-new-image/)): ship the new small image

## Next

Keep ports private with [publish container ports safely](https://levelrail.com/learn/docker/publish-container-ports-safely/)).

## Frequently asked questions

### Why use a multi-stage build?

Compilers, package managers and source files are needed to build but not to run. Leaving them out gives a smaller image with less to patch and less to attack.

### Can I build only one stage?

Yes. docker build --target build . stops at the stage named build, which is handy for debugging.

### Why does my compiled binary fail to start in the final image?

The final image may lack the libraries the binary was linked against, for example a binary built on a glibc image run on Alpine, which uses musl. Build and run on matching bases, or build a static binary.


## Sources

- [Docker docs, multi-stage builds](https://docs.docker.com/build/building/multi-stage/)
