Multi-Stage Builds
A multi-stage build uses one stage to build and a second stage to run. The final image holds only the built result, so it stays slim.
Two stages in one file
The first stage builds, and the second stage runs.
FROM python:3.12-slim AS build
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.12-alpine
WORKDIR /app
COPY --from=build /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY app.py .
CMD ["python", "app.py"]Example
docker build -t g4-multi:1.0 . >/dev/null
docker run --rm g4-multi:1.0
docker images g4-multi --format "{{.Repository}}:{{.Tag}} {{.Size}}"Key points
- Build stage: the image that compiles code or installs packages.
- Runtime stage: the slim image that ships only the result.
- COPY --from=build copies the built files from the first stage.
- The build tools never reach the final image.
- A slim final image downloads faster and has less to attack.
In this example, a multi-stage build compiles nothing heavy and copies only the installed packages into a slim runtime image. The listing shows the final image size. The small size proves the build tools stayed behind in the first stage.
Note
The stages share one Dockerfile, separated by two FROM lines.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does the runtime stage of a multi-stage build hold?