In Spring Boot, you can configure the server port by setting the server.port
property in the application.properties
or application.yml
file.
1. Application Properties and YAML file
Here’s an example of how to configure the server port in application.properties
file:
server.port=8080
In this example, the server will run on port 8080.
You can also configure the server port using the server.port
property in the application.yml
file
server:
port: 8081
In this example, the server will run on port 8081.
2. Configure Port Programmatically
You can also configure the server port programmatically in a Spring Boot application.
@Value("${server.port}")
int port;
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container -> {
container.setPort(port);
});
}
In this example, the port is injected from the properties file, and a EmbeddedServletContainerCustomizer
bean is defined to set the port on the EmbeddedServletContainer
instance used by Spring Boot.
System.getProperties().put( "server.port", 80 );
SpringApplication.run(App.class, args);
3. Spring HTTP Port
You can also use the spring.http.port
property to configure the server port, this property is also supported by Spring Boot.
spring.http.port=8082
In this example, the server will run on port 8082.
4. Through command line
Another way to configure the port is by using the command line argument while running the application like this:
-Dserver.port=8888
or --server.port=8888
java -jar myapp.jar --server.port=8888
or java -jor mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085
ar myapp.jar -Dserver.port=8888
In this example, the server will run on port 8888.
You can also use the SERVER_PORT
environment variable to configure the server port.
export SERVER_PORT=8084
In this example, the server will run on port 8084.