DEV Community
Introduction
Spring Boot applications run on a default port (8080), but sometimes you need to change it for various reasons, such as avoiding conflicts with other applications, running multiple instances, or security considerations. In this blog, we’ll explore different ways to configure the port for a Spring Boot application.
1. Configuring Port in application.properties
The simplest way to set a custom port is by defining it in the application.properties
file.
server.port=9090
This will make the application run on port 9090 instead of the default 8080.
2. Configuring Port in application.yml
If you prefer using YAML, you can configure the port in application.yml
:
server:
port: 9090
Just like the properties file, this will ensure the application starts on port 9090.
3. Setting Port via Command Line Arguments
You can also specify the port when starting the application using a command-line argument:
java -jar myapp.jar --server.port=9090
This is useful when you need to override the port dynamically without modifying configuration files.
4. Setting Port Using Environment Variables
If you want to configure the port using an environment variable, you can set it like this:
On Linux/macOS:
export SERVER_PORT=9090
On Windows:
set SERVER_PORT=9090
This is useful in cloud deployments or containerized environments where configurations are managed via environment variables.
5. Configuring Port Programmatically in Java
If you need more flexibility, you can set the port programmatically in your SpringBootApplication
class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> factory.setPort(9090);
}
}
This approach allows dynamic port configuration based on application logic.
6. Configuring Random Port for Testing
For testing purposes, you might want the application to start on a random port. You can do this by setting:
server.port=0
Or in YAML:
server:
port: 0
Spring Boot will then assign a random available port at runtime.
Conclusion
Configuring the port for a Spring Boot application is straightforward and can be done using properties, YAML, command-line arguments, environment variables, or programmatically. Depending on your use case, choose the method that best fits your deployment strategy.
Do you have any other Spring Boot configuration challenges? Let us know in the comments!
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)