Multi-Stage Build in Docker: What It Is and How It Works
multi-stage build in Docker is a way to use multiple FROM statements in one Dockerfile to create smaller, optimized images by copying only the necessary files from intermediate stages. It helps separate build tools from the final image, reducing size and improving security.How It Works
Think of a multi-stage build like cooking a meal in several steps but only packing the final dish for lunch. In Docker, you start with one stage that includes all the tools and files needed to build your app, like compilers or package managers. Then, in the next stage, you copy only the finished app files into a clean, minimal image without the build tools.
This process uses multiple FROM lines in a single Dockerfile. Each stage can have a name, and you can copy files from one stage to another using --from=stage-name. This way, the final image is smaller because it excludes unnecessary build files, making it faster to download and more secure.
Example
This example shows a multi-stage Dockerfile for a simple Go application. The first stage builds the app, and the second stage creates a small image with just the app binary.
FROM golang:1.20 AS builder WORKDIR /app COPY . . RUN go build -o myapp FROM alpine:3.18 COPY --from=builder /app/myapp /usr/local/bin/myapp CMD ["/usr/local/bin/myapp"]
When to Use
Use multi-stage builds when you want to keep your Docker images small and clean. This is especially useful for compiled languages like Go, Java, or C++, where the build environment is large but the final app is small.
It also helps improve security by excluding build tools and source code from the final image. In real-world projects, multi-stage builds speed up deployment and reduce storage and bandwidth costs.
Key Points
- Multi-stage builds use multiple
FROMstatements in one Dockerfile. - They separate build environment from the final runtime image.
- They reduce image size by copying only needed files.
- They improve security by excluding build tools and source code.
- Supported in Docker 17.05 and later.