Spring Boot learning path Level 1 This level · 16 of 26
Easy java spring

How does Spring Boot decide server port priority?

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.

Could you say this in an interview?

**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):

  1. java -jar app.jar --server.port=9000
  2. SPRING_APPLICATION_JSON='{"server":{"port":9000}}'
  3. -Dserver.port=9000
  4. SERVER_PORT=9000 (environment variable, relaxed binding)
  5. application-{profile}.properties outside the jar, then application.properties outside the jar
  6. Profile files inside the jar, then application.properties inside the jar
  7. 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 the local.server.port property or @LocalServerPort in 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)
  1. Spring Boot how-to: Change the HTTP portdocs.spring.io
  2. Spring Boot how-to: Discover the HTTP port at runtimedocs.spring.io
  3. Spring Boot reference: Externalized configuration orderdocs.spring.io
Previous
Next