Video in progress

What is Spring Boot's layered jar feature, and how does it speed up Docker image updates?

A fat jar can be split into layers: dependencies, the Spring Boot loader, snapshot dependencies, and the application code. If you copy each as its own Docker layer, then when the code changes only a layer of a few hundred kilobytes is updated.

📖 Answer

With a plain COPY app.jar, an 80 MB jar is one layer. You change one line of code and the whole 80 MB is pushed again and pulled again on every node. Yet 79 MB of it is libraries, and they have not changed.

In Spring Boot 3.3+ you can unpack the jar with jarmode=tools (in earlier versions it is jarmode=layertools):

FROM eclipse-temurin:21-jre AS extract
WORKDIR /x
COPY target/app.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --launcher --destination out

FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=extract /x/out/dependencies/ ./
COPY --from=extract /x/out/spring-boot-loader/ ./
COPY --from=extract /x/out/snapshot-dependencies/ ./
COPY --from=extract /x/out/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

The layers are ordered from the least frequently changed to the most. As a result, the registry and the nodes fetch only the application layer anew.

There are alternatives too: Cloud Native Buildpacks (./mvnw spring-boot:build-image) or Google Jib split into the same layers even without a Dockerfile. Which one to pick depends on the team's habits. What matters is that libraries and code sit in separate layers.