Table of Contents
Tomcat supports using the GraalVM Native Image tool to produce a native binary including the container. This documentation page describes the build process of such an image.
The native image tool is much easier to use with single JARs, as a result the process will use the Maven shade plugin JAR packaging (fat JAR). The idea is to produce a single JAR that contains all necessary classes from Tomcat, the webapps and all additional dependencies. Although Tomcat has received compatibility fixes to support GraalVM native images, any library may not be compatible and may require replacement code (the GraalVM documentation has more details about this).
Download and install GraalVM. The first step is then to add the native-image tool.
./gu install native-image
Packaging and Building
Inside the tomcat-maven folder, the directory structure is the same as for regular Tomcat. The main configuration files are placed in the conf folder, and if using the default server.xml the webapps are placed in the webapps folder.
The first step is to build the fat Tomcat JAR with all dependencies. Any JSP in the webapp must all be precompiled and packaged.
ant -Dwebapp.name=somewebapp -f graal-webapp.ant.xml
Native image configuration
Native images do not support any form of dynamic classloading or reflection unless it is defined explicitly in descriptors. Generating them uses a tracing agent from the GraalVM, and needs additional manual configuration in some cases.
Run the GraalVM substrate VM using the trace agent:
Now all paths from the webapp that lead to dynamic classloading (ex: Servlet access, websockets, etc) need to be accessed using a script that will exercise the webapp. Servlets may be loaded on startup instead of needing an actual access. Listeners may also be used to load additional classes on startup.
Once that is done, the VM may be shut down. The descriptors can now be generated from the trace file.
Building the native image
If everything has been done properly, the native image can now be built using the native-image tool.
Running the native image is then:
Servlets, JSPs, EL, websockets, the Tomcat container, tomcat-native, HTTP/2 are all supported out of the box in a native image. However, EL uses BeanInfo reflection which needs manual descriptor configuration. To give an example, the EL expression
At the time of writing this documentation, JULI is not supported as the log manager configuration property is not supported by Graal, in addition to some static initializer problems, and the regular java.util.logging loggers and implementation should be used instead.
If using the default server.xml file, some Server listeners have to be removed from the configuration as they are not compatible with native images, such as a JMX listener (JMX is unsupported) and leak prevention listeners (use of internal code that does not exist in Graal).