Spring Boot’s default port 8080 isn’t always the ideal choice for your applications.
You might need to change it when running multiple services locally, avoiding port conflicts in your development environment, or deploying to production where standard ports are already occupied.

In this comprehensive guide, you’ll discover five distinct methods to configure your Spring Boot application’s port, giving you the flexibility to adapt to various deployment scenarios and development requirements.

1. Using application.properties

The application.properties file is your primary configuration source in Spring Boot applications.

Located in the src/main/resources directory, this file allows you to modify various application settings, including the server port, in a simple key-value format.

You can easily change the default port 8080 to any available port on your system using this approach.

Setting server.port property

Simply add server.port property in your application.properties file to change Spring Boot’s default port.

You simply need to add the line server.port=YOUR_PORT_NUMBER to your configuration file.

For example, if you want to run your application on port 9090, you would add: server.port=9090.

Configuring different profiles

There’s a powerful feature in Spring Boot that lets you maintain different port configurations for various environments.

Different profiles enable you to manage your application’s behavior across various environments efficiently.

For development, you might want to use port 8080, while your production environment might require port 80.

You can create profile-specific properties files like application-dev.properties, application-prod.properties, each with its own server.port setting.

You can activate profiles using the spring.profiles.active property or through command-line arguments as shown below.

# application-dev.properties
server.port=8081 

# application-prod.properties
server.port=8080

This gives you flexibility in managing your application’s port configuration across different environments.

2. Using application.yml Configuration

It is common to use YAML configuration in Spring Boot applications as an alternative to properties files.

YAML offers a more structured and readable format for your configuration settings, making it easier to manage complex configurations and maintain your application’s port settings.

Basic YAML port configuration

An equivalent way to set your Spring Boot application’s port in YAML format is straightforward.

You can specify the server port in your application.yml file using the following syntax:

server: 
  port:8081 

This simple configuration allows you to change the default port from 8080 to any port number you prefer.

Hierarchical configuration structure

While YAML’s hierarchical structure provides better readability compared to properties files, you can organize your server configurations in a nested format.

This approach helps you group related settings together, making your configuration more maintainable as shown below

server:
  port:8081 
  servlet:
    context-path: /api

Multi-environment YAML setup

Similar to application.properties, you can create separate yaml files for different environments using spring profiles.

Corresponding to the active profile specified with spring.profiles.active parameter, the yaml file will be picked up and its configuration will come into effect.

3. Programmatic Port Configuration

WebServerFactoryCustomizer implementation

Programmatic port configuration in Spring Boot offers you fine-grained control over server settings through code.

By implementing WebServerFactoryCustomizer interface, you can customize various server properties, including the port number.

This approach gives you the flexibility to set the port dynamically based on your application’s logic or external conditions.

Here’s how you can do it

@Component 
public class ServerPortCustomizer implements 
             WebServerFactoryCustomizer { 
  @Override 
  public void customize(ConfigurableWebServerFactory factory) { 
    factory.setPort(8085); 
  } 
}

ApplicationRunner approach

There’s another elegant way to configure your Spring Boot application’s port using the ApplicationRunner interface.

This method allows you to modify the server port after the application context has been loaded but before the web server starts.

Implementation of ApplicationRunner involves creating a bean that implements the interface and overriding the run method.

You can inject the ConfigurableWebServerFactory and set your desired port number with its setPort() method.

This approach is particularly useful when you need to determine the port based on some runtime conditions or external service discovery.

@Component 
public class PortConfiguration implements ApplicationRunner { 
  @Autowired 
  private ConfigurableWebServerFactory webServer; 
  
  @Override 
  public void run(ApplicationArguments args) { 
    webServer.setPort(8086); 
  } 
}

Configuration class setup

The configuration class approach provides you with a clean, centralized way to manage your server port settings.

By creating a dedicated configuration class with the @Configuration annotation, you can define beans that handle port customization in one place.

Approach involves creating a configuration class where you can define multiple beans for different server customization needs.

You can combine this with conditional annotations (@ConditionalOnProperty, @Profile) to apply different port configurations based on various environments or conditions.

@Configuration 
public class ServerConfig { 
  @Bean 
  public WebServerFactoryCustomizer webServerFactoryCustomizer() { 
    return factory -> factory.setPort(8087); 
  } 
}

Error handling and fallback options

The error handling mechanism for programmatic port configuration should include fallback options in case your desired port is already in use.

You can implement logic to attempt binding to alternative ports if your primary port is unavailable, log appropriate messages, and ensure your application starts successfully even when facing port conflicts as shown below.

@Component 
public class PortErrorHandler implements 
             WebServerFactoryCustomizer { 
  @Override 
  public void customize(ConfigurableWebServerFactory factory) { 
    try { 
      factory.setPort(8088); 
    } catch (Exception e) { 
      factory.setPort(8089); 
      // Fallback port 
      logger.warn("Primary port unavailable, using fallback port: 8089"); 
    } 
  }
} 

Method 4: Command Line Arguments

Runtime port specification

For quick and flexible port changes without modifying configuration files, you can use command-line arguments when starting your Spring Boot application.

This method allows you to specify the port directly during application launch, making it particularly useful for development and testing scenarios where you need to switch ports frequently.

Command-line syntax options

You can change the port using two different command-line syntaxes: using —server.port or -Dserver.port.

Command-line arguments provide immediate port configuration without touching your application code or configuration files.

You can use --server.port=8081 when running the JAR directly, or -Dserver.port=8081 as a JVM argument.

This flexibility makes it easy to deploy the same application on different ports across various environments.

Priority and override behavior

Assuming you have port configurations in multiple places, command-line arguments take precedence over application.properties, application.yml, and environment variables.

This means that if you specify a port through command-line arguments, it will override any other port configurations in your application.

This allows you to temporarily override the port setting without modifying any configuration files, which is particularly useful in development and testing scenarios.

Random port assignment

You can set your application to use a random available port by setting server.port=0 in your application.properties.

This approach is particularly useful during testing to prevent port conflicts when running multiple instances of your application simultaneously.

Multiple port configuration

The ability to configure multiple ports in Spring Boot allows you to expose different services on separate ports.

This is particularly useful when you need to separate concerns, such as having different ports for HTTP and management endpoints.

Port configuration for multiple endpoints can be achieved through custom server factories. Here’s an example implementation:

@Bean 
public WebServerFactoryCustomizer servletContainer() { 
  return server -> { 
    server.addAdditionalTomcatConnectors(createConnector(8081)); 
    server.addAdditionalTomcatConnectors(createConnector(8082)); 
  }; 
}

SSL/TLS port setup

On implementing secure communication, you can configure SSL/TLS ports in Spring Boot to enable HTTPS.

This involves specifying the SSL port, typically 443, and providing the necessary certificate information in your configuration.

Understanding SSL/TLS port configuration requires proper key store setup and certificate management.

You’ll need to specify following properties in your configuration files to enable secure communication.

server.ssl.key-store=classpath:keystore.jks 
server.ssl.key-store-password=your_password 
server.ssl.key-store-type=JKS 
server.ssl.key-alias=your_alias 
server.port=8443

Final Words

Ultimately, you have multiple flexible options to modify Spring Boot’s default port 8080 based on your specific needs.

Whether you prefer the simplicity of application.properties, the structured approach of YAML, the dynamic control of programmatic configuration, or the convenience of environment variables, each method offers unique advantages.

By understanding these approaches, you can effectively customize your application’s port settings across different deployment environments and scenarios.

Choose the method that best aligns with your project requirements and development workflow.

Categorized in:

Spring Boot,