How do you build a Docker image for a Java application efficiently?
IntermediateConceptJava builds (Maven, Gradle, JAR, WAR)
Answer
Short answer
Use a multi-stage Dockerfile: build with a Maven + JDK image, then copy only the JAR into a small JRE image. Copy pom.xml and download dependencies before copying source code, so Docker caches the dependency layer and rebuilds are fast. Run as a non-root user.
Example
# ---- build stage ----
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /src
COPY pom.xml .
RUN mvn -B -ntp dependency:go-offline # cached until pom.xml changes
COPY src ./src
RUN mvn -B -ntp package -DskipTests
# ---- runtime stage ----
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
RUN addgroup -S app && adduser -S app -G app
COPY --from=build /src/target/*.jar app.jar
USER app
EXPOSE 8080
HEALTHCHECK CMD wget -qO- http://localhost:8080/actuator/health || exit 1
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
Why each part matters
| Choice | Benefit |
|---|---|
| Multi-stage | Final image has no Maven, JDK or source code — ~200 MB instead of ~700 MB |
pom.xml copied first |
Code changes don't re-download dependencies |
| JRE base | Fewer packages → fewer CVEs |
Non-root USER |
Limits damage if the app is compromised |
-DskipTests here |
Tests already ran in the CI stage before the image build |
Alternatives
Jib (mvn jib:build) builds optimised images without a Dockerfile or Docker daemon; Spring Boot buildpacks (mvn spring-boot:build-image) do the same.
What to say in the interview
"Multi-stage build: Maven/JDK stage to compile, JRE stage to run. I copy the pom first and resolve dependencies to get layer caching, run as non-root and set MaxRAMPercentage. Jib is a good alternative when we don't want a Docker daemon in CI."
All Build Tools (Java, Node.js, Python, .NET) questions Roadmap: Java apps: Maven, Gradle, JAR & WAR
More on Java builds (Maven, Gradle, JAR, WAR)
What is pom.xml and what is it used for?BeginnerHow do you build and run a Java project with Maven?BeginnerWhat is the difference between a JAR and a WAR file?BeginnerWhat is Gradle and how is it different from Maven?BeginnerHow do you configure a Spring Boot application for different environments?BeginnerA Maven build fails in the pipeline with "Could not resolve dependencies". How do you fix it?Intermediate