Sobes.tech
Junior — Middle

Have you used multi-stage Docker images in your projects to optimize the build?

sobes.tech AI

Answer from AI

Yes, multi-stage Docker images allow for significant optimization of the final container size and faster build times. You can use multiple stages in a single Dockerfile: the first stage builds the application with necessary tools, and subsequent stages copy only the required artifacts into a minimal base image.

Example for a Python project:

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

This approach prevents including build tools and temporary files in the final image, reducing size and increasing security.