Sobes.tech
Junior — Middle

Can you explain the principle of multi-stage builds in Docker and why they are used?

sobes.tech AI

Answer from AI

Multi-stage build in Docker allows creating images in multiple steps, which helps reduce the final image size and improve security.

The idea is to build and compile the application with all necessary tools and dependencies in the initial stages, then copy only the required files into a minimal base image in the final stage.

Advantages:

  • Smaller final image size by excluding build tools.
  • Increased security as the final image lacks unnecessary build tools.
  • Simplified Dockerfile with all stages described in one file.

Example:

# Build stage
FROM openjdk:17-jdk AS build
WORKDIR /app
COPY . .
RUN ./gradlew build

# Run stage
FROM openjdk:17-jre
WORKDIR /app
COPY --from=build /app/build/libs/myapp.jar ./
CMD ["java", "-jar", "myapp.jar"]

Here, the application is built with JDK, then only the ready jar file is copied into a minimal JRE image.