The embedded Tomcat server
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Installing a separate web server on every laptop, lab machine and cloud server is slow and easy to get wrong. A shop API should start with one command, wherever it runs.
Embedded server in the jar vs a WAR on an external server
An embedded server is a web server that runs inside your application as a library. Spring Boot's web starter puts Tomcat in your jar and starts it from main, so java -jar app.jar is a complete web server for your app.
The files inside the boot-lab jar, listed with jar tf: your classes, and every library, Tomcat included.
Example 1 · What is inside the boot-lab jar
Runs in: the boot-lab practice project (Spring Boot 4.1)
./mvnw packagejar tf target/boot-lab-0.0.1-SNAPSHOT.jarMETA-INF/MANIFEST.MF ... BOOT-INF/classes/application.properties BOOT-INF/classes/com/shoplite/lab/BootLabApplication.class BOOT-INF/classes/com/shoplite/lab/HelloController.class ... BOOT-INF/lib/jackson-databind-3.1.5.jar ... BOOT-INF/lib/spring-webmvc-7.0.9.jar BOOT-INF/lib/tomcat-embed-core-11.0.24.jar BOOT-INF/lib/tomcat-embed-el-11.0.24.jar BOOT-INF/lib/tomcat-embed-websocket-11.0.24.jar ...
What this code does
jar tflists the files inside a jar (thejartool comes with the JDK). Your classes are underBOOT-INF/classes, and every library, Tomcat included, is a jar inside the jar underBOOT-INF/lib.- That is why
java -jar target/boot-lab-0.0.1-SNAPSHOT.jaris all a server needs: Java 17 or newer, and no Tomcat installed. - The jar is about 20 MB, mostly libraries. Boot's own loader (under
org/springframework/boot/loader, trimmed here) knows how to read jars nested inside a jar.
The older way is a WAR (web archive) file: you install Tomcat on a server, copy the WAR into it, and Tomcat runs your app (often several apps at once). Configuration is split between your code and the server, and "it works on my machine" problems come from different Tomcat versions.
With the embedded server, the Tomcat version is part of your build (11.0.24 in Boot 4.1.1), each app has its own server, and the same jar runs on your laptop, in the lab and in the cloud. Boot can still build a WAR for companies that need one, but new projects use the jar.
server.port and the context path
A context path is a prefix in front of every URL of the app, such as /shop, set with server.servlet.context-path. The default is none ('/' in the log). The port is set separately with server.port, default 8080.
A controller on port 9090 under /shop, called with and without the context path.
Example 2 · HelloController.java and application.properties
Runs in: the boot-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/HelloController.javapackage com.shoplite.lab;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class HelloController {
@GetMapping("/api/hello") public String hello() { return "Hello from ShopLite, served by " + Thread.currentThread(); }}
# src/main/resources/application.propertiesspring.application.name=boot-labserver.port=9090server.servlet.context-path=/shop... TomcatWebServer : Tomcat initialized with port 9090 (http) ... TomcatWebServer : Tomcat started on port 9090 (http) with context path '/shop' ... BootLabApplication : Started BootLabApplication in 4.394 seconds (process running for 5.394)
What this code does
- The two properties move the whole app: Tomcat now listens on 9090, and every URL starts with
/shop. The controller code did not change. - The startup log confirms both values. Read it before you test, so you call the right address.
- For this lesson, remove the two quiet lines from
application.propertiesagain: the Tomcat lines are INFO messages.
Example 3 · Calling the app with and without the context path
Runs in: the boot-lab practice project (Spring Boot 4.1)
curl -i http://localhost:9090/shop/api/hellocurl -i http://localhost:9090/api/helloHTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 70 Date: Fri, 16 Oct 2026 05:13:51 GMT Hello from ShopLite, served by Thread[#41,http-nio-9090-exec-2,5,main] HTTP/1.1 404 Content-Type: text/html;charset=utf-8 Content-Language: en Content-Length: 431 Date: Fri, 16 Oct 2026 05:13:52 GMT <!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title>...</html>
What this code does
- With
/shopin front, the request reaches the controller. The thread namehttp-nio-9090-exec-2is a Tomcat worker thread, explained in the fourth section. - Without it, the request never reaches Spring at all: Tomcat itself answers with its plain HTML 404 page, not Spring's JSON error. An HTML 404 is a hint that the context path or port is wrong.
Set both in application.properties, or for one run on the command line: java -jar app.jar --server.port=9090. A command-line value wins over the file. server.port=0 picks a free random port, which tests use.
ShopLite keeps the defaults: port 8080 on your laptop, and no context path, because its URLs already start with /api. A context path is mostly useful when several apps share one address behind a gateway.
Predict the output
Which address answers?
Read the settings and pick the result.
Round 1 of 2
Which URL reaches the controller?
'Port 8080 was already in use'
Starting a second copy of boot-lab while the first one still listens on port 8080.
Example 4 · Starting a second copy on port 8080
Runs in: the boot-lab practice project (Spring Boot 4.1)
java -jar target/boot-lab-0.0.1-SNAPSHOT.jar... 2026-10-16T10:44:33.249+05:30 INFO 23700 --- [boot-lab] [ main] o.s.boot.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http) ... 2026-10-16T10:44:34.081+05:30 WARN 23700 --- [boot-lab] [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'webServerStartStop' ... 2026-10-16T10:44:34.139+05:30 ERROR 23700 --- [boot-lab] [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
What this code does
- The first copy (properties back to the defaults) already listens on 8080. The second one builds the whole context, then cannot open the port, stops Tomcat and exits.
- The usual culprit is your own app still running in another terminal or in the IDE (a second Run click). Other programs that like 8080: Jenkins, XAMPP's Tomcat, another Spring project.
- The fixes are in the OS steps of this section: find the process and stop it, or start this app on another port.
"Port 8080 was already in use" means another process is already listening on that port, and only one process can listen on a port at a time. Boot reports it as APPLICATION FAILED TO START. Most of the time the other process is your own app: a run you forgot in another terminal, or an IDE run that is still going after you clicked Run again. Find its process ID (PID), check what it is, and stop it, or start this app on another port.
The commands differ by computer. On Windows, run netstat -ano | findstr :8080 (the PID is the last column of the LISTENING line), check it with tasklist | findstr <pid>, and stop it with taskkill /PID <pid> /F. On macOS, run lsof -i :8080 (the PID column), then kill <pid>, and kill -9 <pid> only if it still listens after a few seconds. Run the first command again: no output means the port is free.
One thread per request: the Tomcat thread pool and virtual threads
A thread pool is a set of ready threads that Tomcat reuses to serve requests, one thread per request. The default is up to 200 (server.tomcat.threads.max); a thread returns to the pool when its request is done.
Three 5-second requests sent at once to a pool of 2 threads, then the same with virtual threads.
# three 5-second requests at once, pool of 2 platform threadsjava -jar target/boot-lab-0.0.1-SNAPSHOT.jar --server.tomcat.threads.max=2# request 1: 200 after 5.29s request 2: 200 after 5.27s request 3: 200 after 10.22s# the same with virtual threads (Java 21)java -jar target/boot-lab-0.0.1-SNAPSHOT.jar --server.tomcat.threads.max=2 --spring.threads.virtual.enabled=true# request 1: 200 after 5.73s request 2: 200 after 5.72s request 3: 200 after 5.63sExample 5 · Platform threads, then virtual threads (Java 21)
Runs in: the boot-lab practice project on Java 21
# run 1: java -jar target/boot-lab-0.0.1-SNAPSHOT.jarcurl http://localhost:8080/api/hellocurl http://localhost:8080/api/hello# run 2: java -jar target/boot-lab-0.0.1-SNAPSHOT.jar --spring.threads.virtual.enabled=truecurl http://localhost:8080/api/hellocurl http://localhost:8080/api/helloHello from ShopLite, served by Thread[#40,http-nio-8080-exec-1,5,main] Hello from ShopLite, served by Thread[#41,http-nio-8080-exec-2,5,main] Hello from ShopLite, served by VirtualThread[#43,tomcat-handler-0]/runnable@ForkJoinPool-1-worker-1 Hello from ShopLite, served by VirtualThread[#54,tomcat-handler-1]/runnable@ForkJoinPool-1-worker-1
What this code does
- Run 1: each request gets a worker from Tomcat's pool,
http-nio-8080-exec-1,-exec-2, and so on. These are ordinary (platform) threads; the pool keeps up to 200 of them. - Run 2: each request gets a new virtual thread (
tomcat-handler-0,-1), carried by a small pool ofForkJoinPoolworker threads. Your controller code is the same. - On Java 17 the property is ignored silently and you keep seeing
http-nio-8080-exec-N: virtual threads need Java 21 or newer.
The thread runs your controller, service and database code, so while your code waits for MySQL or another API, its thread waits too. If every pool thread is busy, new requests queue until one is free: with a pool of 2, two requests finish after 5 seconds and the third after 10.
Virtual threads (Java 21) are very cheap threads managed by the JVM, so Tomcat can give every request its own new one instead of borrowing from a fixed pool. Turn them on with spring.threads.virtual.enabled=true: the three requests then finish in about 5 seconds. Your code stays the same; only blocking waits get cheaper.
Graceful shutdown so in-flight requests finish
Graceful shutdown means that when the app is told to stop, Tomcat first stops accepting new requests and waits for the running ones to finish, then closes. In Spring Boot 4 it is the default (server.shutdown=graceful).
The two settings that control it, and a slow request that survives Ctrl+C.
# application.properties (graceful is already the default; writing it documents the choice)server.shutdown=gracefulspring.lifecycle.timeout-per-shutdown-phase=20sExample 6 · A slow request survives a shutdown
Runs in: the boot-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/HelloController.javapackage com.shoplite.lab;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class HelloController {
@GetMapping("/api/hello") public String hello() { return "Hello from ShopLite, served by " + Thread.currentThread(); }
@GetMapping("/api/report") public String slowReport() throws InterruptedException { Thread.sleep(5000); // pretend the monthly sales report takes 5 seconds return "Monthly report ready"; }}(terminal 2) curl -i http://localhost:8080/api/report (terminal 1) Ctrl+C, about 2 seconds later terminal 1: 2026-10-16T10:47:31.862+05:30 INFO 11900 --- [boot-lab] [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed initialization in 2 ms 2026-10-16T10:47:34.156+05:30 INFO 11900 --- [boot-lab] [ Thread-1] o.s.boot.tomcat.GracefulShutdown : Commencing graceful shutdown. Waiting for active requests to complete 2026-10-16T10:47:37.007+05:30 INFO 11900 --- [boot-lab] [tomcat-shutdown] o.s.boot.tomcat.GracefulShutdown : Graceful shutdown complete terminal 2: HTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 20 Date: Fri, 16 Oct 2026 05:17:36 GMT Monthly report ready
What this code does
- The request started, then the app was told to stop. Tomcat stopped taking new requests ("Commencing graceful shutdown"), waited for the report, and finished about 3 seconds later ("Graceful shutdown complete"). The client still got its 200.
- With
server.shutdown=immediatethe same test cuts the request: curl printscurl: (52) Empty reply from serverand the log showsjava.lang.InterruptedException: sleep interrupted. - In a real app that cut request could be an order half saved or a UPI payment confirmed with no reply to the phone.
The wait has a limit: spring.lifecycle.timeout-per-shutdown-phase, 30 seconds by default. Requests still running after that are cut. ShopLite sets 20 seconds in its project, which is plenty for its requests.
A stop request comes from Ctrl+C, the IDE's stop button, or a deployment tool replacing the app with a new version. Graceful shutdown makes those stops safe for users. kill -9 or taskkill /F cannot be graceful: they end the JVM at once.
Next step
Check your understanding
11 quick questions