Junior — Middle
Explain the concept of multi-stage Docker image build and why it is used.
sobes.tech AI
Answer from AI
Multi-stage Docker image build allows using multiple build stages within a single Dockerfile. This helps create compact and optimized images by separating build stages from runtime stages.
In the first stage, you can use an image with tools for compiling and building the application, and in subsequent stages — only a minimal image with the files necessary for running.
Advantages:
- Significantly reduces the size of the final image.
- Eliminates unnecessary dependencies and tools from the final image.
- Simplifies maintenance and updating of the Dockerfile.
Example:
# Build stage
FROM openjdk:11-jdk AS build
WORKDIR /app
COPY . .
RUN ./gradlew build
# Runtime stage
FROM openjdk:11-jre
WORKDIR /app
COPY --from=build /app/build/libs/myapp.jar ./
CMD ["java", "-jar", "myapp.jar"]