The 30 second answer
The server port follows the normal precedence rules for server.port. A command-line argument overrides a Java system property, which overrides SERVER_PORT from the environment, followed by configuration files, with external files ahead of packaged ones. Without an override, the default is 8080. Setting the port to zero asks the operating system for an available port. A WebServerFactoryCustomizer can also set it programmatically, so its ordering matters if customizers change the same setting.
**1. server.port is a bound property.** ServerProperties is @ConfigurationProperties("server") and has a nullable port field (ServerProperties.java L60-L66). A customizer copies it to the factory only when it is set:
map.from(this.serverProperties::getPort).to(factory::setPort);ServletWebServerFactoryCustomizer.java L66
2. The fallback is 8080. The factory itself starts with:
private int port = 8080;AbstractConfigurableWebServerFactory.java L40
3. Priority of sources (high to low, common ones):
java -jar app.jar --server.port=9000SPRING_APPLICATION_JSON='{"server":{"port":9000}}'-Dserver.port=9000SERVER_PORT=9000(environment variable, relaxed binding)application-{profile}.propertiesoutside the jar, thenapplication.propertiesoutside the jar- Profile files inside the jar, then
application.propertiesinside the jar - Factory default 8080
4. Programmatic override. A customizer bean runs after the properties customizer when it has a later order, so it can win:
@Bean
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> portCustomizer() {
return factory -> factory.setPort(9090);
}Special values:
server.port=0: random free port. Read it from thelocal.server.portproperty or@LocalServerPortin tests.server.port=-1: the web server is not started, but the application context still is a web context.management.server.port: Actuator on a separate port.
Editor's note: in containers, prefer the SERVER_PORT environment variable so the image does not change between environments.
Sources (3)
- Spring Boot how-to: Change the HTTP portdocs.spring.io
- Spring Boot how-to: Discover the HTTP port at runtimedocs.spring.io
- Spring Boot reference: Externalized configuration orderdocs.spring.io