'How to provide runtime JVM arguments to created layered image using Spring Boot?

I try using a new feature of Spring Boot that crafts a Docker image as of Spring Boot 2.3.0.M1. I work with Java 16 using preview features and Spring Boot 2.5.1-SNAPSHOT supporting this feature.

This is my plugin configuration in pom.xml assuming layers.xml exists and is picked up correctly:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
        <layers>
            <configuration>${project.basedir}/src/main/layers.xml</configuration>
        </layers>
    </configuration>
</plugin>

An here is Dockerfile:

FROM openjdk:16-jdk-slim AS builder
WORKDIR source
ARG JAR_FILE=target/whatever-name-of-the-application.jar
COPY ${JAR_FILE} application.jar
RUN --env JAVA_OPTS="--enable-preview"
RUN java -Djarmode=layertools -jar application.jar extract

FROM openjdk:16-jdk-slim
WORKDIR application
COPY --from=builder source/dependencies/ ./
COPY --from=builder source/spring-boot-loader/ ./
COPY --from=builder source/snapshot-dependencies/ ./
COPY --from=builder source/application/ ./
ENTRYPOINT ["java", "org.springframework.boot.loader.JarLauncher"]

Now comes time to run mvn spring-boot:build-image and the image is created, so I run the application through docker run <hash>. The run fails because the preview mode is not enabled.

Setting Active Processor Count to 8
Calculating JVM memory based on 11470756K available memory
Calculated JVM Memory Configuration: -XX:MaxDirectMemorySize=10M -Xmx11069703K -XX:MaxMetaspaceSize=93852K -XX:ReservedCodeCacheSize=240M -Xss1M (Total Memory: 11470756K, Thread > Count: 50, Loaded Class Count: 14156, Headroom: 0%)
Adding 129 container CA certificates to JVM truststore
Spring Cloud Bindings Enabled
Picked up JAVA_TOOL_OPTIONS: -Djava.security.properties=/layers/paketo-buildpacks_bellsoft-liberica/java-security-properties/java-security.properties -XX:+ExitOnOutOfMemoryError -XX:ActiveProcessorCount=8 -XX:MaxDirectMemorySize=10M -Xmx11069703K -XX:MaxMetaspaceSize=93852K -XX:ReservedCodeCacheSize=240M -Xss1M -Dorg.springframework.cloud.bindings.boot.enable=true
Exception in thread "main" java.lang.UnsupportedClassVersionError: Preview features are not enabled for com/nikolascharalambidis/sandbox/springboot/reactivestack/ReactiveStackApplication (class file version 60.65535). Try running with '--enable-preview'
        at java.base/java.lang.ClassLoader.defineClass1(Native Method)
        at java.base/java.lang.ClassLoader.defineClass(Unknown Source)
        ...

How to enable preview using Spring Boot Maven plugin for layered Docker images? To extend the question: How to provide runtime JVM arguments?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source