Docker and Layered Jars

Why Layers

Dependencies (50 MB) rarely change; your code (500 KB) changes every commit. If the jar is one Docker layer, every build re-uploads 58 MB. Spring Boot can split the jar into layers so Docker caches the big unchanged ones.

Example

java -Djarmode=tools -jar target/shopease-1.0.0.jar list-layers

Example output

dependencies
spring-boot-loader
snapshot-dependencies
application

A Multi-Stage Dockerfile

Example

Dockerfile

# ---- build stage ----
FROM eclipse-temurin:21-jdk AS build
WORKDIR /src
COPY .mvn .mvn
COPY mvnw pom.xml ./
RUN ./mvnw -q dependency:go-offline
COPY src src
RUN ./mvnw -q package -DskipTests
RUN java -Djarmode=tools -jar target/*.jar extract --layers --launcher --destination /extracted

# ---- runtime stage ----
FROM eclipse-temurin:21-jre
RUN useradd --system --uid 10001 shopease
WORKDIR /app
COPY --from=build /extracted/dependencies/ ./
COPY --from=build /extracted/spring-boot-loader/ ./
COPY --from=build /extracted/snapshot-dependencies/ ./
COPY --from=build /extracted/application/ ./
USER shopease
EXPOSE 8080
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75"
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

Example

Build and run:

docker build -t shopease:1.0.0 .
docker run -p 8080:8080 -e SPRING_PROFILES_ACTIVE=prod shopease:1.0.0

Example output

 => CACHED [runtime 4/7] COPY --from=build /extracted/dependencies/ ./
 => [runtime 7/7] COPY --from=build /extracted/application/ ./
 => naming to docker.io/library/shopease:1.0.0
INFO  c.s.ShopEaseApplication : Started ShopEaseApplication in 4.106 seconds

Note: jarmode=tools and the extract command are Spring Boot 3.3+. On 3.2 and earlier use -Djarmode=layertools -jar app.jar extract.

No Dockerfile at All

Example

Buildpacks create an optimised, layered image directly from Maven:

./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=shopease:1.0.0

Example output

[INFO]  > Running creator
[INFO]     [creator]     Paketo Buildpack for BellSoft Liberica 10.x
[INFO]     [creator]     Paketo Buildpack for Spring Boot 5.x
[INFO] Successfully built image 'docker.io/library/shopease:1.0.0'

Tip: The Docker material on Careeroza covers images, volumes and networks in depth.