Sobes.tech
Junior — Middle

What are the advantages of using multi-stage builds in Docker and what are they used for?

sobes.tech AI

Answer from AI

Multi-stage build in Docker allows creating images consisting of multiple stages, where each stage can use its own base image and perform specific tasks (e.g., build, testing, packaging). Main advantages:

  • Reducing the size of the final image: only necessary artifacts are copied in the final stage, excluding build tools and intermediate files.
  • Enhanced security: development tools are absent in the final image, reducing the attack surface.
  • Convenience and cleanliness: the build process can be divided into logical stages, improving Dockerfile readability.

It is used to create optimized, compact, and secure containers, especially when the build process requires heavy tools that are not needed in production.

Example:

# Build stage
FROM maven:3.8-jdk-11 AS builder
WORKDIR /app
COPY . .
RUN mvn clean package

# Final stage
FROM openjdk:11-jre-slim
COPY --from=builder /app/target/myapp.jar /app/myapp.jar
CMD ["java", "-jar", "/app/myapp.jar"]