Junior — Middle
What is the purpose of multi-stage builds in Docker, and when is it advisable to use them?
sobes.tech AI
Answer from AI
Multi-stage builds in Docker allow creating multiple intermediate images in a single Dockerfile and copying only the necessary artifacts from them into the final image. This helps significantly reduce the size of the final image and separates the build stages from the runtime stage.
Main advantages:
- Minimizing the size of the final image by excluding build tools and temporary files.
- Enhancing security, as the final image does not contain unnecessary utilities and source code.
- Simplifying Dockerfile maintenance, since all stages are described in one file.
It is advisable to use multi-stage builds when the application requires complex building processes (e.g., compilation, dependency installation), but only the compiled artifacts are needed for running.
Example:
# Build stage
FROM python:3.10-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
COPY . .
RUN python setup.py build
# Final stage
FROM python:3.10-alpine
WORKDIR /app
COPY --from=builder /app/build /app
CMD ["python", "app.py"]
In this example, dependencies are installed and the application is built during the builder stage, and only the build result is included in the final image without build tools and pip cache.