Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 111 ยท Dockerfiles

Multi-Stage Builds

Learn Docker multi-stage builds: separate build and runtime stages, COPY --from, named stages, --target, scratch images, running tests, and real size savings.

To compile a program you need a compiler, headers, package managers and often hundreds of megabytes of tooling. To run the program you need almost none of that. In the early days of Docker, people either shipped the whole toolbox inside the final image (huge, and full of things an attacker would love to find) or wrote clumsy shell scripts that built the program in one container and copied it into another. Multi-stage builds solve this inside a single Dockerfile: you use as many FROM lines as you need, do the heavy work in early stages, and copy only the results into a small final stage.

In this lesson you will build the same tiny Go program two ways, compare the sizes, learn how stages are named and targeted, see how BuildKit decides which stages to run, and pick up patterns for tests, scratch images and copying from other images. All commands and sizes come from real builds.

The problem: one stage does it all

Take a small Go program, main.go:

Go
package main

import (
	"fmt"
	"os"
)

func main() {
	name := "world"
	if len(os.Args) > 1 {
		name = os.Args[1]
	}
	fmt.Printf("Hello, %s!\n", name)
}

with a one-line go.mod (module hello, go 1.25). The obvious Dockerfile builds it in the official Go image and runs it there:

DOCKERFILE
FROM golang:1.25-alpine
WORKDIR /src
COPY go.mod main.go ./
RUN go build -o /hello .
ENTRYPOINT ["/hello"]
CONSOLE
$ docker build -t hello-single -f Dockerfile.single .
$ docker run --rm hello-single Docker
Hello, Docker!
$ docker images hello-single --format '{{.Size}}'
374MB

It works, but 374 MB is the size of the entire Go toolchain, for a program that prints one line. The final image also carries the compiler, the source code and the build cache. All of it is extra download time, extra storage and extra attack surface.

The solution: two stages

A multi-stage Dockerfile has several FROM instructions. Each starts a new, independent stage with its own filesystem. You can copy files from an earlier stage into a later one with COPY --from. Only the last stage becomes the image you get; everything else is thrown away (it stays in the build cache, but it is not part of the result).

DOCKERFILE
# ---- build stage ----
FROM golang:1.25-alpine AS build
WORKDIR /src
COPY go.mod main.go ./
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /hello .

# ---- runtime stage ----
FROM alpine:3.22
COPY --from=build /hello /usr/local/bin/hello
USER 10001
ENTRYPOINT ["hello"]
CONSOLE
$ docker build -t hello-multi .
$ docker run --rm hello-multi Docker
Hello, Docker!
$ docker images --filter reference='hello-*' --format 'table {{.Repository}}\t{{.Size}}'
REPOSITORY     SIZE
hello-multi    15MB
hello-single   374MB

Same program, same output, 15 MB instead of 374 MB: about 25 times smaller. Here is the mental model:

TEXT
 Stage "build" (golang:1.25-alpine)        Stage 2 (alpine:3.22)  <- the final image
 +-------------------------------+         +---------------------------+
 | Go compiler, std library      |         | Alpine base (~9 MB)       |
 | /src/main.go                  |         |                           |
 | go build -> /hello  ----------+--COPY-->+ /usr/local/bin/hello       |
 +-------------------------------+  --from +---------------------------+
        discarded (cache only)

Check what actually ended up in the final image. It has the program and nothing to build with:

CONSOLE
$ docker history hello-multi --format '{{.Size}}\t{{.CreatedBy}}' | head -5
0B	ENTRYPOINT ["hello"]
0B	USER 10001
1.53MB	COPY /hello /usr/local/bin/hello # buildkit
0B	CMD ["/bin/sh"]
8.97MB	ADD alpine-minirootfs-3.22.7-x86_64.tar.gz /โ€ฆ
$ docker run --rm --entrypoint sh hello-multi -c 'which go; echo "go found? exit=$?"'
go found? exit=1

The only content we added is the 1.53 MB binary on top of the Alpine base. (The -ldflags="-s -w" flags strip debugging information, and CGO_ENABLED=0 makes a static binary that does not depend on the build image's C libraries, which matters when the runtime image is different.)

The lesson is not about Go. The same idea applies to Java (JDK to build, JRE to run), Node.js (build a frontend with all dev dependencies, serve static files from nginx), Rust, .NET, C++ and more. See the language recipes for each.

How COPY --from works

COPY --from=<source> <src> <dest> copies files from another stage, another image or the build context's earlier result, instead of from your project directory. The source can be:

  • A stage name: COPY --from=build /hello /usr/local/bin/hello.
  • A stage number counting from 0: COPY --from=0 .... Fragile: inserting a stage changes the numbers. Prefer names.
  • Any image from a registry, with no stage needed. Docker pulls it behind the scenes:
DOCKERFILE
FROM alpine:3.22
COPY --from=nginx:1.27-alpine /etc/nginx/nginx.conf /tmp/nginx.conf
CMD ["head", "-3", "/tmp/nginx.conf"]
CONSOLE
$ docker build -t ext-demo .
$ docker run --rm ext-demo

user  nginx;
worker_processes  auto;

Copying from an image is a convenient way to borrow one file (a static binary, a config template, a certificate bundle) without building on top of that whole image. Adding --chown and --chmod works the same as for ordinary copies (COPY and ADD).

Naming stages and picking a target

Name a stage with AS <name> after the image in FROM. Names are lowercase and are used by COPY --from, by FROM <name> (to build on top of an earlier stage) and by the --target flag of docker build.

Here is a more realistic Dockerfile with four stages: a shared base, a test stage, the build, and a minimal final image.

DOCKERFILE
FROM golang:1.25-alpine AS base
WORKDIR /src
COPY go.mod main.go ./

FROM base AS test
COPY main_test.go ./
RUN go test ./...

FROM base AS build
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /hello .

FROM scratch AS final
COPY --from=build /hello /hello
ENTRYPOINT ["/hello"]

FROM base AS test starts a new stage from the end of base, so it inherits the working directory and the copied files. FROM scratch is the empty image: no shell, no libraries, no files at all except what you copy in. A static Go binary needs nothing else.

Without --target, the last stage wins

CONSOLE
$ docker build --progress=plain -t hello-final .
...
#5 [base 1/3] FROM docker.io/library/golang:1.25-alpine@sha256:...
#6 [base 2/3] WORKDIR /src
#7 [base 3/3] COPY go.mod main.go ./
#8 [build 1/1] RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /hello .
#9 [final 1/1] COPY --from=build /hello /hello
$ docker images hello-final --format '{{.Size}}'
2.2MB
$ docker run --rm hello-final Scratch
Hello, Scratch!

Two things to notice. First, the final image is only 2.2 MB: just the binary. Second, the log has no test stage at all. BuildKit (the default builder) builds only the stages the target depends on, working backwards from the last FROM. The test stage is not needed by final, so it was skipped. Unrelated stages do not slow you down.

A scratch image has no shell, so there is nothing to debug with. Trying to open one fails right away:

CONSOLE
$ docker run --rm --entrypoint sh hello-final
docker: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: error during container init: exec: "sh": executable file not found in $PATH

That is a feature for security and a cost for debugging; Debugging Containers shows ways around it.

Building a specific stage with --target

docker build --target <stage> stops at that stage and tags it, which is useful for running tests, for a debug image, or for inspecting an intermediate result:

CONSOLE
$ docker build --progress=plain --target test -t hello-test .
...
#8 [test 1/2] COPY main_test.go ./
#9 [test 2/2] RUN go test ./...
#9 13.33 ok  	hello	0.005s
$ docker build -q --target build -t hello-build .
$ docker images hello-build --format '{{.Size}}'
373MB

The test stage ran go test inside the build image, and a failure there would fail the build with a non-zero exit code. That makes docker build --target test . a neat step for CI: no test tools on the CI machine, identical environment every time. The build stage on its own is, as expected, as big as the toolchain image (373 MB). The shipped final image was 2.2 MB.

BuildKit skips stages nothing depends on, so a test stage that is not wired into the final stage will not run in a plain docker build. The simple, reliable way to enforce tests is a separate CI step: run docker build --target test . first, and build the final image only if it succeeds.

Parallel stages and caching

Stages that do not depend on each other are built in parallel by BuildKit. In this Dockerfile, a and b each take eight seconds to produce a file, and the final stage needs both:

DOCKERFILE
FROM alpine:3.22 AS a
RUN sleep 8 && echo a > /a.txt
FROM alpine:3.22 AS b
RUN sleep 8 && echo b > /b.txt
FROM alpine:3.22
COPY --from=a /a.txt /
COPY --from=b /b.txt /
CMD ["cat", "/a.txt", "/b.txt"]
CONSOLE
$ time docker build -q --no-cache -t par .
...
real	0m11s
$ docker run --rm par
a
b

Eleven seconds, not sixteen: the two slow steps ran at the same time. This is one reason to split a big build into independent stages (build the frontend and the backend side by side, for instance).

Every stage also uses the normal build cache (The Build Cache). Put rarely changing steps (installing dependencies from a manifest) in early positions of each stage, and you get fast incremental builds and a small final image. If you need to refresh a single stage, --no-cache-filter <stage> does that.

Variables are scoped to a stage too: an ARG or ENV declared in one stage is not visible in another (ENV and ARG). Redeclare what you need in each stage.

Typical patterns

Compiled languages: build, then run with a minimal base.

DOCKERFILE
FROM golang:1.25-alpine AS build
...
FROM scratch            # or alpine, or a distroless image
COPY --from=build /app /app

Frontend plus web server (read-only example, it needs a real project):

DOCKERFILE
FROM node:lts-alpine AS build
WORKDIR /web
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:1.27-alpine
COPY --from=build /web/dist /usr/share/nginx/html

The final image holds a web server and a folder of static files. node_modules, which can be hundreds of megabytes, never reaches it.

Interpreted languages: install in one stage, copy the result. For Python you can build wheels or a virtual environment in a "builder" stage that has compilers, then copy /venv into a clean slim image. For PHP, run composer install in a Composer stage and copy vendor/ into the runtime image.

One Dockerfile, several outputs. A dev stage with debugging tools and a prod stage without them, selected with --target:

CONSOLE
$ docker build --target dev -t myapp:dev .
$ docker build --target prod -t myapp:1.0 .

Choosing the final stage's base

The size and risk of the image are decided by the final FROM:

Final base Size of a small static program Notes
scratch 2.2 MB (our Go example) Nothing but your files. No shell, no CA certificates, no time zone data, no users. You must add what you need.
alpine 15 MB (our Go example) Tiny but has a shell and package manager, good for debugging.
debian:*-slim, ubuntu tens of MB more Needed when your binary uses glibc or you want familiar tools.
Distroless images similar to scratch plus basics No shell; includes CA certs and users. See Choosing a Base Image.

Remember what scratch lacks: if your program makes HTTPS requests, copy a CA certificate bundle in (COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/). For USER, use a numeric ID such as USER 10001, since scratch has no /etc/passwd. Also make sure the binary is static: a dynamically linked binary built on glibc will not start on Alpine (musl) or scratch, and the error looks like exec ... no such file or directory.

Mistakes to avoid

  • Copying too much. COPY --from=build /src /app brings the source tree and any build output into the final image. Copy exactly the artifacts you need.
  • Forgetting the runtime needs. The binary might need shared libraries, config files, templates, or migration scripts. Run the final image before you call it done.
  • Using the wrong architecture or libc. A binary built in a glibc image will not run on Alpine; build and run on compatible bases or build statically.
  • Hiding secrets in a build stage. Discarded stages are not in the final image, but they remain in the build cache on your machine. Still use BuildKit secret mounts instead of copying credentials (BuildKit and buildx).
  • Putting the build tool in the final stage by habit. If you find yourself running apt-get install build-essential in the stage that ships, it probably belongs in an earlier stage.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Dockerfile has three FROM instructions and you run docker build -t app . with no extra flags. Which stage becomes the image?

    Without --target the builder uses the final stage as the result. Earlier stages exist only to produce files for later ones.
  2. 2. What does COPY --from=build /hello /usr/local/bin/hello do?

    --from picks the source: a stage name, a stage number or an image. The files are copied (not moved) into the stage that contains the COPY.
  3. 3. Your Dockerfile has a stage named test that nothing else depends on. What happens during a plain docker build . with BuildKit?

    BuildKit works backwards from the target and builds only what it depends on. Use --target test to run it, or make another stage depend on it.
  4. 4. Why does a Go binary built with the default settings in golang:alpine and copied into scratch sometimes fail with 'no such file or directory'?

    The message refers to the missing dynamic loader or libraries. Build a static binary (for Go, CGO_ENABLED=0) before copying into scratch.
  5. 5. Which flag builds only up to a given stage and tags that stage as the result?

    docker build --target <stage> stops at the named stage. It is used for test and debug stages or to choose between dev and prod outputs.

Summary

  • A multi-stage Dockerfile uses several FROM lines; each starts a fresh stage, and only the last stage (or the one chosen with --target) becomes the image.
  • Build in an early stage with the full toolchain; copy only the finished artifacts into a small runtime stage with COPY --from=<stage>. Our Go example shrank from 374 MB to 15 MB on Alpine and to 2.2 MB on scratch.
  • Name stages with AS name. COPY --from can also copy from stage numbers or from any image.
  • BuildKit builds only the stages the target needs, and runs independent stages in parallel; each stage uses the build cache normally.
  • --target lets you build and run a test stage, a debug image or a dev/prod variant from one Dockerfile.
  • Choose the final base on purpose: scratch and distroless for the smallest and most locked-down images, Alpine or slim Debian when you need a shell or glibc. Build static binaries for scratch, and add CA certificates and numeric users yourself.
  • ARG and ENV are scoped to a stage; copy exactly what you need, not whole directories.

Next: BuildKit and buildx