How to use CRaC with Spring Boot in a Docker Container
Transcript
Coordinated Restore at Checkpoint (CRaC) is an OpenJDK project designed to reduce the startup and warmup times of Java applications to just milliseconds. This tutorial demonstrates how to use CRaC with Spring Boot applications running in a Docker container. To follow along, you’ll need Docker (ensure it’s up and running) and a Spring Boot application (version 3.2 or later) since CRaC is supported in these versions. For this example, we’ll use the Spring Boot Petclinic application, which can be found on GitHub. Additionally, we’ll use the Liberica Runtime Container with CRaC support, available on Docker Hub and tagged with “CRaC.”
Open the application in your preferred IDE (e.g., IntelliJ IDEA). No modifications to the application code are necessary—simply add the CRaC project dependency to the pom.xml file (assuming you’re using Maven). You’ll also need a Dockerfile for containerizing the application. In the first stage of the Dockerfile, we use the Liberica Runtime Container based on Liberica JDK Lite 21 and Alpaquita Linux with musl support. This container supports CRaC (indicated by the CRaC tag). Here, we copy the project into the image and package it as a JAR file. In the second stage, we use the Liberica Runtime Container based on JRE to create a layered JAR (recommended by Spring). Finally, we assemble all the layers into a new image using Liberica JRE with CRaC support and define the ENTRYPOINT to create a snapshot when the application exits.
Next, we containerize the application using the docker build command and run it in a container. To create a checkpoint, enable the CAP_CHECKPOINT_RESTORE and SYS_PTRACE capabilities using the --cap-add flag. If your Linux kernel version is older than 5.9, you can use the --privileged flag, though it’s not recommended for production. Once checkpointed, the application logs its activity using the CRaC API. Create a fresh image with a checkpoint using the docker commit command and update the ENTRYPOINT to restore the application from the snapshot. Remove the previous container (docker rm -f) and start the application from the snapshot, specifying the port and required capabilities. The application will start in milliseconds. You can launch multiple Petclinic instances in separate containers by specifying unique ports and container names. To verify the application, open it in a browser—it should run without issues. For copy-and-paste code snippets, refer to the dedicated guide linked in the description box of the video.