Chapter 2 · Lesson 13 of 20
Docker

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.

By the end you will

Build an app in one stage and ship a small final image with only the result.

Time
18 min
Level
Intermediate
Check
4 questions
You need
  • Docker installed
  • A project with an npm build script that writes to dist

A multi-stage build uses several FROM lines in one 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:

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

SymptomLikely causeFix
COPY failed: file not foundThe path after --from=build is wrongCheck where the build writes, for example with docker run --rm mysite:build ls /app
invalid from flag valueThe stage name does not match ASMake the names identical, including case
failed to solve with an unknown stage--target names a stage that does not existCheck the AS names in the Dockerfile
Final image is still hugeThe last stage copied too much, or starts from a large baseCopy only the output folder and use a smaller base
exec format error when startingImage built for a different CPU architectureRebuild with --platform matching the server
Build is slow every timeSource copied before dependencies installCopy package*.json first, install, then copy the rest
Site shows nginx welcome pageOutput folder is empty or named differentlyCheck the build script’s output directory
npm ci fails in the build stageNo lock file was copied into the stageCopy package-lock.json along with package.json
Build is fast locally but slow in CIThe layer cache is not kept between runsCache 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 for the cache rule and moves COPY package*.json above the source copy, so rebuilds reuse the build cache. He runs the result with a loopback-only port, as in publish container ports safely.

Quick reference#

TaskCommand or line
Name a stageFROM node:22 AS build
Copy from a stageCOPY --from=build /app/dist /usr/share/nginx/html
Build up to one stagedocker build --target build -t app:build .
Compare sizesdocker image ls app
Build for another CPUdocker build --platform linux/amd64 .
Inspect a stage’s filesdocker run --rm app:build ls /app

Next#

Keep ports private with publish container ports safely.

Check what you learned4 questions
1What does COPY --from=build /app/dist /usr/share/nginx/html do?
2You get invalid from flag value. What is the most likely cause?
3What does docker build --target build . do?
4A secret is passed with ARG in the build stage. Is it safe because that stage is not shipped?

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

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios