Skip to content

Multi-stage builds: compile big, ship small

Select an icon to see what it is.

Step 6 of 6

The size difference

A single-stage build would ship the whole Go image, hundreds of megabytes. The multi-stage image is alpine plus one binary, roughly ten megabytes. You can stop at any stage with --target.

$ docker build --target builder -t web:builder .
PrevNext

docker images (sizes are illustrative)

web:builder several hundred MB (Go toolchain + source + binary)
web:1.0 about 10 MB (alpine + binary)

Try it yourself

Build a tiny Go program both ways and compare sizes.

$ printf 'package main\nimport "fmt"\nfunc main() { fmt.Println("hello") }\n' > main.go
$ printf 'module web\ngo 1.22\n' > go.mod
$ printf 'FROM golang:1.22 AS builder\nWORKDIR /src\nCOPY . .\nRUN CGO_ENABLED=0 go build -o /out/web .\n\nFROM alpine\nCOPY --from=builder /out/web /web\nCMD ["/web"]\n' > Dockerfile
$ docker build -t web:1.0 .
$ docker build --target builder -t web:builder .
$ docker images web

Quiz

1. What does the final image contain from the builder stage?
2. Why is the multi-stage image smaller?
3. How do you build only the first stage?