Junior — Middle
Have you used multi-stage builds when creating Docker images?
sobes.tech AI
Answer from AI
Yes, multi-stage build in Docker allows creating lighter and optimized images by dividing the build process into several stages. For example, you can first build the application with necessary dependencies, and then copy only the final result into a minimal base image, excluding all build tools.
An example Dockerfile with multi-stage build for a Python application:
# Build stage
FROM python:3.9-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
COPY . .
# Final image stage
FROM python:3.9-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 reduces the size of the final image and increases security, as build tools are absent in the final image.