For a long time, the Apache Tomcat team has maintained a page with instructions on how to embed Tomcat in a wider range of applications. The page covers a few popular application servers, but not Spring Boot. Recently, the Tomcat team moved the embedded documentation to the main Tomcat documentation site and added a section on frequently asked questions about Tomcat.
There are a few ways to embed Tomcat in a Spring Boot application. The easiest way is to add the spring-boot-starter-tomcat
dependency to your project, and Spring Boot will automatically configure Tomcat for you. Spring Boot also supports a few other Embedded Containers.
If you want more control over the configuration of Tomcat, you can add the tomcat-embed-core
dependency to your project, and Spring Boot will auto-configure a TomcatEmbeddedServletContainerFactory
for you. You can then customize the factory by setting properties on it. For example, you can set the port that Tomcat listens on.
If you need even more control, you can instantiate a Tomcat
instance yourself and [add](https://tomcat.apache.org/tomcat-9.0-doc/setup.html#Adding_Connectors_and_Services_ Programmatically) connectors and services to it. Spring Boot can then wrap the Tomcat instance in a TomcatEmbeddedServletContainer
.
Here is a sample project that shows how to embed Tomcat in a Spring Boot application:
The sample project has two connectors configured: an HTTP connector on port 8080, and an AJP connector on port 8009. The AJP connector is commented out by default. To use it, uncomment the <!--
and -->
tags around the <Connector>
element in src/main/resources/application.properties
.
You can then build and run the sample application with the following command:
$ ./mvnw spring-boot:run
The application will start up on port 8080. You can access the application at http://localhost:8080/. You can also access the application through the AJP connector at http://localhost:8009/.