Sobes.tech
Junior — Middle

What is the advantage of using multi-stage build when creating Docker images?

sobes.tech AI

Answer from AI

The advantage of Multi-stage build in Docker is the ability to create compact and optimized images by dividing the build process into multiple stages.

Main benefits:

  • In the first stage, a large image with necessary build tools (e.g., compilers, dependencies) can be used.
  • In subsequent stages, only the necessary artifacts (e.g., compiled binaries or files) are copied, excluding all unnecessary components.
  • As a result, a minimal-sized image is produced, which speeds up loading and deployment.
  • The number of vulnerabilities is reduced because development tools are absent in the final image.

Example Dockerfile with multi-stage build:

# Build stage
FROM python:3.10-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
COPY . .

# Final stage
FROM python:3.10-alpine
COPY --from=builder /root/.local /root/.local
COPY --from=builder /app /app
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "/app/main.py"]

Here, dependencies are installed and the application is built in the first stage, and in the second — a minimal image with only the necessary files is created.