Sub topic 5
The Embedded Web Server
This chapter assumes you can read basic Java and Maven. You should also know what a servlet container such as Tomcat does at a high level, and you should have seen the starters chapter. After it, you will know where the web server in a Spring Boot application comes from and how to configure, swap, and test it. You will also know how to diagnose the most common startup errors.
From deployed WAR to embedded server
Before Spring Boot, a typical Java web application was packaged as a WAR file (a web archive). You installed a servlet container such as Tomcat on a machine, configured it, and copied the WAR into it. The container owned the process. Your code was a guest.
Spring Boot reverses this. The server is a library on your classpath, and your main method starts it. Your application owns the process, and the server runs inside it. Packaging, startup, and configuration all follow from this inversion:
- The build output is one executable JAR that contains your code, your libraries, and the server.
java -jaris the whole deployment procedure. No separate server installation is needed.- The server version is a dependency like any other, pinned by the Spring Boot parent.
- Server settings live in
application.propertieswith the rest of your configuration, not in aserver.xmlon a host.
Where the server comes from
You never declare Tomcat directly. The web starter pulls it in. This is the dependency block from your project:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>spring-boot-starter-web depends on spring-boot-starter-tomcat, which depends on the embedded Tomcat libraries. To confirm this on your own project, print the dependency tree:
./mvnw dependency:treeLook for spring-boot-starter-tomcat and tomcat-embed-core under the web starter. Their presence on the classpath is what makes Boot choose Tomcat, as the next section explains.
How auto-configuration picks and starts the server
Starting the server is auto-configuration at work. It is not special-cased in main. The sequence is:
SpringApplication.runinspects the classpath. If servlet classes and Spring MVC are present, it creates a servlet web application context. If it finds the reactive stack (WebFlux) instead, it creates a reactive context. With neither, the application is not a web application and no server starts.- Web server auto-configuration registers a factory bean,
ServletWebServerFactory. Each server has its own conditional configuration. The Tomcat one applies only when Tomcat classes are present. - While the context refreshes, it asks the factory to create the server. The server is created and bound to its port, but request handling is not yet open.
- Spring registers the
DispatcherServlet, the front controller that routes requests to your@RestControllermethods. - At the end of the refresh, the server starts accepting connections. Boot logs a line like
Tomcat started on port 8080 (http).
One consequence matters for debugging. Because the server is created during context refresh, a bean that fails to start prevents the port from ever opening. If curl gets "connection refused", read the startup log before suspecting the network.
Choosing a different server
Boot supports several embedded servers. Which ones are available depends on your Boot version, so check the reference documentation for yours.
| Server | Stack | Starter |
|---|---|---|
| Tomcat | Servlet (default) | `spring-boot-starter-tomcat`, included by the web starter |
| Jetty | Servlet | `spring-boot-starter-jetty` |
| Undertow | Servlet | `spring-boot-starter-undertow`, not available in the newest Boot releases |
| Reactor Netty | Reactive (default for WebFlux) | included by `spring-boot-starter-webflux` |
To switch servlet servers, exclude the Tomcat starter from the web starter and add the replacement. This example switches to Jetty:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
</dependencies>Your controller code does not change, because it depends on Spring MVC and not on the server. The startup log now says Jetty started on port 8080.
Common server properties
Server settings use the server.* prefix. Put them in application.properties:
server.port=8081
spring.application.name=demoThe properties below are the ones you will reach for most often.
| Property | Effect |
|---|---|
| `server.port` | Port to listen on. The default is 8080. A value of `0` picks a random free port. |
| `server.address` | Network interface to bind to. `127.0.0.1` accepts local connections only. |
| `server.servlet.context-path` | Prefix for every URL. With `/api`, your endpoint becomes `/api/hello`. |
| `server.tomcat.threads.max` | Maximum request-handling threads in Tomcat. The default is 200. |
| `server.shutdown` | Set to `graceful` to finish in-flight requests before stopping. |
| `spring.lifecycle.timeout-per-shutdown-phase` | How long graceful shutdown waits, for example `30s`. |
| `server.ssl.*` | Enables HTTPS using a key store or certificate bundle you supply. |
Server-specific tuning uses a server-specific prefix, such as server.tomcat.* or server.jetty.*. If you switch servers, these properties stop applying. Boot ignores unknown properties without complaint, so a leftover server.tomcat.threads.max under Jetty has no effect and produces no error.
The thread-per-request model
On a servlet server, each incoming request occupies one worker thread until the response is written. With 200 threads, the 201st simultaneous request waits in a queue. If your handlers block on slow databases or remote calls, the thread pool becomes your concurrency limit. Two options exist when that limit hurts. You can raise the thread count, which costs memory per thread. On Java 21 or later with a recent Boot 3.x release, you can instead set spring.threads.virtual.enabled=true to run request handling on virtual threads. Measure before changing either setting.
Random ports and graceful shutdown
Setting server.port=0 sounds odd but is useful. Several instances can run on one machine without clashing, and tests never collide with a developer's running app. The chosen port is available at runtime as the property local.server.port.
Graceful shutdown matters when the application is stopped while serving traffic. Without it, the server closes immediately and in-flight requests fail. With server.shutdown=graceful, the server stops accepting new connections and gives active requests time to finish, up to the configured timeout.
Testing against a real server
Spring's test support can start the full embedded server on a random port. Here is a test for the /hello endpoint from the first-endpoint chapter, using only the JDK HTTP client:
package com.example.demo;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class HelloServerTest {
@Value("${local.server.port}")
int port;
@Test
void helloIsServedOverRealHttp() throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest
.newBuilder(URI.create("http://localhost:" + port + "/hello"))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.body()).isEqualTo("Hello, Spring Boot!");
}
}RANDOM_PORT starts a real server, so the request goes through sockets, the servlet container, and the DispatcherServlet. The default webEnvironment of MOCK does not open a port at all. It is faster but does not exercise the server.
Common errors
- "Web server failed to start. Port 8080 was already in use." Another process holds the port, often a previous run of your own app. Stop that process or change
server.port. On Linux or macOS,lsof -i :8080shows the owner. - The app starts and exits immediately. The web starter is missing, or the dependency was declared with the wrong scope. The classpath check found no web stack, so Boot created a plain context with no server. Without a non-daemon server thread, the JVM ends.
- Your server change had no effect. Both servers are on the classpath. Run
./mvnw dependency:treeand look for the excluded one. - 404 on every URL after setting a context path. All URLs now carry the prefix. Request
/api/hello, not/hello. - The app works with
java -jarbut not in an external Tomcat. Deploying to an external container needs WAR packaging and the embedded Tomcat markedprovided. This is a different setup from the one in this tutorial.
Trade-offs of embedding
Embedding makes deployment simple and keeps the server version in your control, but it has costs. Every application carries its own server copy, so a server security patch means rebuilding and redeploying each application. Operations teams used to managing shared containers must adapt to managing many small processes. For most teams, especially those using containers, the simplicity and reproducibility outweigh these costs.
Exercise
Your project uses spring-boot-starter-web. You add spring-boot-starter-jetty to the dependencies but make no other change. The startup log still says "Tomcat started". Why, and what is the fix?
Show answer
spring-boot-starter-web already brings spring-boot-starter-tomcat, so both servers are on the classpath and Boot prefers Tomcat. The fix is to exclude spring-boot-starter-tomcat from the spring-boot-starter-web dependency. After that, only Jetty is on the classpath and the log shows "Jetty started".
Exercise
A test starts the application with the default webEnvironment and tries to send an HTTP request to localhost, but gets "connection refused". What setting fixes this, and what does it do?
Show answer
Use @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOMPORT). The default MOCK environment does not start a real server and opens no port. RANDOMPORT starts the embedded server on a free port, which the test reads from the local.server.port property.