Video in progress

What is a multi-stage Docker build, and how does it help a Java application?

One Dockerfile has several FROM stages: in the first, the jar is built with the JDK and Maven, and only the finished jar is copied into the last one. The result is a small, clean image and an identical build on any machine.

📖 Answer

# Stage 1: build
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY mvnw pom.xml ./
COPY .mvn .mvn
RUN ./mvnw -B dependency:go-offline
COPY src src
RUN ./mvnw -B package -DskipTests

# Stage 2: run
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /src/target/*.jar app.jar
USER 10001
ENTRYPOINT ["java", "-jar", "app.jar"]

In the final image only the layers after the last FROM remain. Maven, the source code, the .m2 cache: all of it stays behind in the build stage.

The second benefit is mentioned less often: the build environment is pinned in the Dockerfile. Differences like Java 17 on a developer's laptop and Java 21 in CI go away.

The downside: if the Maven cache is not preserved in CI, the build can be slow. That is why some teams build the jar in CI as usual and leave only the second stage in the Dockerfile. Both approaches work. What matters is that the final image has no build tools.