Spring Boot with CDS in Docker

This is just a short post about Class Data Sharing (CDS), a feature of the JVM, that helps reducing startup time and memory footprint. Spring has already a good tutorial about this topic.

The only thing, that is missing for me, is Docker. Because all my Spring Boot applications are bundled in Docker containers. This also solves the problem, that the generated CDS Archive is for the right JVM version, you are running it later with.

My normal Dockerfile for Spring Boot applications just looks like this:

FROM eclipse-temurin:17-jre
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app.jar"]

For adding CDS we need to add one line for creating the CDS Archive and change one line for using the archive. After copying the jar, we run the command to create the archive:

RUN java -XX:ArchiveClassesAtExit=application.jsa -Dspring.context.exit=onRefresh -jar /app.jar

The “-XX:ArchiveClassesAtExit=application.jsa” is for creating the CDS Archive. Followed by “-Dspring.context.exit=onRefresh” to convince Spring to exit at the right point after loading everything but before starting everything, you can read the Spring Boot CDS documentation for more information on this. The last part is only the starting of the jar “ -jar /app.jar”.

Now we need to change the entry point to load the archive:

ENTRYPOINT ["java", "-XX:SharedArchiveFile=application.jsa", "-jar", "/app.jar"]

This is it. That was quite easy, so here is the full Dockerfile:

FROM eclipse-temurin:17-jre
COPY target/*.jar app.jar
RUN java -XX:ArchiveClassesAtExit=application.jsa -Dspring.context.exit=onRefresh -jar /app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-XX:SharedArchiveFile=application.jsa", "-jar", "/app.jar"]

For my small example project the amount of saved time was not that huge, but I think real world projects should benefit much more from this. Without CDS my example reported:

Started Application in 6.906 seconds (process running for 7.968)

With CDS:

Started Application in 5.345 seconds (process running for 6.556)

So 1.5 seconds speedup on startup time. If you try this with your projects, please comment the speedup below. Thx and bye.

Leave a Reply