Multi-stage builds

Leave build tools in a build stage

Lesson 11 of 20 · 12 min · Module 4: Artifact and stack design

Only copy the built output into the stage that will run in production.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Name the intermediate stage
  • Copy the artifact rather than the whole build environment

The idea

Image instructions are an ordered build contract. A later instruction can change a default established earlier; the final stage determines the output image.

FROM node:22-alpine AS compiler
WORKDIR /site
COPY . .
RUN npm run build
FROM nginx:1.27-alpine
COPY --from=compiler /site/dist/ /usr/share/nginx/html/

01Name the intermediate stage

AS build gives a stable reference to the stage that holds build tools and generated files. The final stage starts from its own base.

02Copy the artifact rather than the whole build environment

COPY --from selects files from an earlier stage. A static site runtime needs its output, rather than the Node toolchain that produced it.

03Inspect the final stage

The image configuration comes from the last stage by default. In this model, copies and runs are tracked per stage so a comment cannot pretend to create a second image.

Your turn

Create a stage named build from node:22-alpine. Work in /app, COPY . ., and RUN npm run build. Start a final stage from nginx:1.27-alpine and COPY --from=build /app/dist/ /usr/share/nginx/html/.

What the checks look for

  • Uses two distinct build stages
  • Builds in the first stage
  • Copies only the built output into nginx
Try it in the editor →

Take this with you

Separate building an artifact from operating it.

Go a little further

Rename the build stage and update its COPY reference.

Learn Docker & Containers for free

20 short lessons with real code and instant checks.

See the whole course →