Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How do you set the server port and context path in Spring Boot, how do you start on a random port in tests, and how does the application find out which port it got?

We set the port with server.port=8081 and the context path with server.servlet.context-path=/api (spring.webflux.base-path for WebFlux). server.port=0 picks a free port, and in tests @SpringBootTest(webEnvironment = RANDOM_PORT) does the same; the application finds the port it got through @LocalServerPort in tests or a WebServerInitializedEvent listener calling getWebServer().getPort(). The values can also come from SERVER_PORT or --server.port=9090, and management.server.port can move Actuator to a separate port with its own network and security rules.

Background to this question

The port and the path are the address of our service, so every client, proxy, health check and test depends on them. Spring Boot makes them easy to set, but there are several details that matter in real systems: how tests avoid port clashes, how code learns a port chosen at random, and what happens when Actuator moves to its own port. In this answer, we will set the port and path, see how they can be overridden from outside, start on a random port in tests and read it back, and then look at the separate management port and how it can break Kubernetes probes.

1Setting the Port and the Context Path

The embedded server listens on port 8080 by default and serves the application at the root path /. The context path is a prefix added in front of every URL the application serves, so with /api a controller mapped to /orders is reached at /api/orders.

Java
# application.properties, Spring MVC
server.port=8081
server.servlet.context-path=/api
# application.properties, WebFlux (no servlet context)
server.port=8081
spring.webflux.base-path=/api
@GetMapping("/orders")
List<Order> orders() { ... }
// GET http://localhost:8081/api/orders -> 200
// GET http://localhost:8081/orders -> 404

Notice the different property for WebFlux. The context path is a Servlet concept, so it lives under server.servlet; a reactive application has no servlet context, and its prefix is spring.webflux.base-path instead.

2Overriding From the Environment and the Command Line

Because these are ordinary Spring Boot properties, they follow the usual precedence: command-line arguments beat environment variables, which beat application.properties packaged in the jar. Environment variables use relaxed binding, where SERVER_PORT maps to server.port and SERVER_SERVLET_CONTEXT_PATH maps to server.servlet.context-path.

Shell
$ java -jar orders.jar # port 8081 from application.properties
$ SERVER_PORT=9000 java -jar orders.jar # port 9000 from the environment
$ SERVER_PORT=9000 java -jar orders.jar --server.port=9090
# Tomcat started on port 9090 (http) with context path '/api' // the command line wins
Where server.port can come from (higher wins)
SourceExampleTypical use
Command-line argument--server.port=9090Local runs, one-off overrides
Environment variableSERVER_PORT=9000Containers and Kubernetes
Profile fileapplication-prod.propertiesPer-environment defaults
application.properties in the jarserver.port=8081The service default
Spring Boot default8080Nothing set

This is why containers usually set SERVER_PORT in the deployment rather than baking a port into the image: the same jar runs anywhere and the platform decides the port.

3Starting on a Random Port in Tests

Integration tests that start a real server must not clash with each other or with something already running on 8080. server.port=0 asks the operating system for any free port. In tests, @SpringBootTest with webEnvironment = RANDOM_PORT does the same, and @LocalServerPort injects the port the server actually got.

Java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrdersApiTest {
@LocalServerPort int port; // for example 52417, different on every run
@Test
void listsOrders() {
RestClient client = RestClient.create("http://localhost:" + port + "/api");
String body = client.get().uri("/orders").retrieve().body(String.class);
assertThat(body).startsWith("["); // passes
}
}

Notice that the test still has to add the context path, /api, itself. In recent Boot versions the auto-configured test clients, such as TestRestTemplate, already know the port and the context path, so we can use relative URLs with them; @LocalServerPort is for code that builds its own client.

4How Application Code Finds the Port

Outside tests, code sometimes needs the real port, for example to register itself with a discovery service when it started on port 0. The server publishes an event once it is running, and the event gives access to the server and its port.

Java
@Component
class PortLogger {
@EventListener
void onStarted(WebServerInitializedEvent event) {
String ns = event.getApplicationContext().getServerNamespace(); // null for the main server
int port = event.getWebServer().getPort();
log.info("server {} listening on {}", ns == null ? "main" : ns, port);
}
}
// server main listening on 52417
// server management listening on 52418 // only when Actuator runs on its own port

The second log line shows a catch: when Actuator has its own port, its server fires the same event, so a listener must check the server namespace to know which port it is looking at. Boot also writes the ports to the environment as local.server.port and local.management.port once they are known.

5A Separate Port for Actuator

management.server.port puts Actuator endpoints on their own server, for example 9090, while the application stays on 8080. That is useful for security: the main port can be exposed through the load balancer while the management port is reachable only inside the cluster. But it is a second listener with its own network rules, firewall rules and security configuration, and everything that calls Actuator, such as probes and metric scrapers, must use the new port.

YAML
server.port=8080
management.server.port=9090
# /actuator/health is now at http://pod:9090/actuator/health
# http://pod:8080/actuator/health -> 404
# Kubernetes probes must follow the port
livenessProbe:
httpGet: { path: /actuator/health/liveness, port: 9090 }
readinessProbe:
httpGet: { path: /actuator/health/readiness, port: 9090 }
Step throughA probe pointed at the wrong port
kubeletMain server :8080Management :9090
GET /actuator/health/liveness
404: Actuator is not here
three failures: restart the container
after fixing the probe port: GET liveness
200 UP

5 messages in order. Play them, or step through them one at a time.

Moving Actuator without moving the probes turns a healthy pod into a restart loop.

6Follow-up questions

Why can a separate management port break Kubernetes probes if misconfigured?

Two ways. If the probes still point at the main port after Actuator moves, every probe gets a 404, liveness fails, and Kubernetes restarts healthy pods in a loop. And even when the probes target the management port correctly, they check a different server: the management server can answer UP while the main server is not accepting traffic, so readiness no longer reflects whether users can be served. Boot can also expose the probe paths on the main port, with management.endpoint.health.probes.add-additional-paths=true, which makes /livez and /readyz available on the application port.

Does the context path apply to Actuator?

On the same port, yes: with context path /api, health is at /api/actuator/health. With a separate management port it does not, and management.server.base-path sets a prefix for the management server instead.

Is server.port=0 safe in production?

Only when something reads the chosen port and tells clients, such as a service registry. In Kubernetes the container port must be known in advance for Services and probes, so a fixed port is the norm there.

7Conclusion

In this answer, we set the port with server.port and the prefix with server.servlet.context-path, or spring.webflux.base-path for WebFlux, and saw that both can be overridden by SERVER_PORT or --server.port following the usual precedence. We started on a random port with server.port=0 or RANDOM_PORT, read it back with @LocalServerPort or a WebServerInitializedEvent listener, and saw that a separate management.server.port needs its own network rules and correctly pointed probes.

What to say in the interviewAbout 80 seconds aloud

Open with

The port is server.port, for example 8081, and the context path is server.servlet.context-path, for example /api, so a controller at /orders is served at /api/orders. For WebFlux there is no servlet context, so the prefix is spring.webflux.base-path.

Then, if they want more

These are normal properties, so they follow the usual precedence: a command-line argument like --server.port=9090 beats an environment variable like SERVER_PORT, which beats application.properties. In containers I set SERVER_PORT in the deployment. For tests, server.port=0 asks the OS for a free port, and @SpringBootTest with webEnvironment RANDOM_PORT does that for us, so tests never clash.

To find out which port was chosen, a test uses @LocalServerPort, and application code can listen for WebServerInitializedEvent and call getWebServer().getPort(); Boot also sets local.server.port.

If I set management.server.port, Actuator runs on its own server, which is good for keeping it inside the cluster, but it needs its own network and security rules, and that listener also fires the event, so I check the namespace.

The follow-up risk is probes: if they still point at the main port they get 404 and Kubernetes restarts healthy pods, and if they point at the management port they check a server that may be up while the main one is not.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do you set the server port and context path in Spring Boot, how do you start on a...": https://scrivio-interview-library.netlify.app/spring-boot/embedded-servers/1fbe55f371/