Background
Spring Boot is a very popular framework for building microservices. Nowadays packaging a Spring Boot application as a Docker container is very common practice. In this blog post, we will see how we can create a Spring Boot application using GraalVM.
Example Code
This article is based on working code that you can find on GitHub.
Setting up the project
Let’s create a simple Spring Boot application that returns a hello world message.
curl https://start.spring.io/starter.zip -d dependencies=web,devtools \
-d bootVersion=3.0.2.RELEASE -o demo.zip
Now, let’s unzip the file and import the project in your favorite IDE. Add the following code to the HelloWorldController.java
file.
@RestController
public class HelloWorldController {
@GetMapping("/hello")
public Map<String, String> helloWorld() {
return Map.of("message", "Hello World!");
}
}
Creating a Docker image without GraalVM
Install jdk using sdkman.
sdk install java 19.0.2-open
sdk use java 19.0.2-open
Now, let’s create a Docker image for this application using spring boot plugin.
./gradlew bootBuildImage --imageName=local.dev/example
Now, let’s run the docker image and test it.
docker run --rm -p 8080:8080 local.dev/example
curl localhost:8080/hello
Create a Docker image using GraalVM
Install graalvm using sdkman.
sdk install java 22.3.r19-grl
sdk use java 22.3.r19-grl
Add graalvm plugin to the build.gradle
file.
plugins {
...
id 'org.graalvm.buildtools.native' version '0.9.17'
}
Use graalvm native compiler to compile the application and run as standalone application without using jre.
./gradlew nativeBuild
./build/native/nativeCompile/demo
Build the native image.
./gradlew bootBuildImage --imageName=local.dev/example-native
This will take some time to build the native image. Now, let’s run the docker image and test it.
docker run --rm -p 8081:8080 local.dev/example
curl localhost:8081/hello
Conclusion
In this blog post, we saw how we can create a Spring Boot docker image using GraalVM.