Typorithm · medium

Multi-Stage Builds

multistagedevopsmulti-stageoptimizationsize
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Multi-Stage Builds

0%

Images

A multi-stage build compiles in a heavy stage then uses COPY --from to copy only the final artifact into a small base, so the shipped image has no build tools, is much smaller, and has a tinier attack surface. Distroless and alpine bases are common for production.

A multi-stage Dockerfile has more than one FROM. The first stage, named with AS build, carries the full compiler toolchain and produces a binary.

The second FROM starts a fresh, minimal image. COPY --from=build pulls just the compiled artifact out of the build stage, leaving the compiler, source, and intermediate files behind.

The result is a small production image with no build tools — faster to pull, with a smaller attack surface. Distroless and alpine bases are popular final stages for exactly this reason.

01

Multiple FROM lines define separate stages.

02

COPY --from=build copies only the final artifact.

03

The final image has no build tools, so it is small.

FROM golang:1.22 AS build
RUN go build -o app
FROM alpine:3.20
COPY --from=build /app /app
CMD ["/app"]

Read the implementation

Connect each part of the code to the concept before you type.

1. Build stage

FROM ... AS build names a stage that carries the heavy toolchain used only to compile.

FROM golang:1.22 AS build

2. Compile

RUN compiles the binary inside the build stage, where the full Go toolchain is available.

RUN go build -o app

3. Final base

A second FROM starts the final, small runtime image with no build tools.

FROM alpine:3.20

4. Copy artifact

COPY --from=build pulls only the compiled binary out of the build stage into the slim image.

COPY --from=build /app /app

5. Run artifact

CMD runs the copied binary; nothing from the build toolchain ships in the final image.

CMD ["/app"]

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Multi-Stage Builds: Lesson & Practice · Typorithm | ApplyDjinn