Sobes.tech
Junior — Middle

When implementing Docker files, did you use multi-stage builds with multiple stages?

sobes.tech AI

Answer from AI

Yes, multi-stage builds are often used when writing Dockerfiles. This allows creating multiple build stages within a single Dockerfile, where the initial stages handle building and compiling, and the final stage copies only the necessary artifacts to run the application.

Advantages:

  • Reduces the size of the final image, as intermediate files and build tools are not included.
  • Increases security, as development tools are not present in the final image.

Example Dockerfile with multi-stage build for a Python application:

# 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-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY --from=builder /app .
ENV PATH=/root/.local/bin:$PATH
CMD ["python", "app.py"]

Thus, only the necessary dependencies and code are included in the final image, without build tools.