how to change localhost port in spring boot

Spring Boot Application Properties: Server Configuration

Application Properties and Configuration Files

Spring Boot utilizes externalized configuration, allowing application properties to be defined outside the compiled application. These properties can be set via configuration files, environment variables, command-line arguments, or even custom PropertySource implementations. Configuration files are typically named application.properties or application.yml (or .yaml) and are located in the src/main/resources directory.

Server Port Specification

The default port on which a Spring Boot application's embedded web server (typically Tomcat, Jetty, or Undertow) listens is 8080. This default can be overridden using the server.port property.

Property Configuration Examples

  • application.properties: server.port=9000
  • application.yml:
    server: port: 9000 

Alternative Configuration Methods

Besides configuration files, server properties can be defined through:

  • Environment Variables: Setting the environment variable SERVER_PORT=9000 will override the value specified in configuration files. Spring Boot automatically converts environment variables to application properties by replacing underscores with dots and converting to lowercase.
  • Command-Line Arguments: Passing --server.port=9000 as a command-line argument when starting the application. This has the highest precedence and will override values specified in configuration files or environment variables.

Secure Port Configuration (HTTPS)

For HTTPS configuration, the server.port property defines the unsecured port. Additional properties such as server.ssl.key-store, server.ssl.key-store-password, and server.ssl.key-alias are required to configure SSL. To specify a secured port, consider using profiles with different configurations based on the active profile (e.g., application-https.properties). Then, configure the port and keystore properties accordingly within that profile's configuration file.

Considerations and Best Practices

  • Precedence: Command-line arguments take precedence over environment variables, which take precedence over external configuration files, which take precedence over default Spring Boot properties.
  • Profiles: Utilizing Spring profiles allows for different port configurations based on the environment (e.g., development, testing, production).
  • Port Availability: Ensure that the specified port is available and not already in use by another application. Common errors include java.net.BindException: Address already in use, indicating a port conflict.