How to change the default port in Spring Boot
Default, Spring Boot web application starts embedded web server (Tomcat, Jetty, etc.) in port 8080
. And we can configure or change the port using the server.port
property.
Table of contents
- 1. application.properties
- 2. application.yml
- 3. Command Line
- 4. Environment Variable
- 5. WebServerFactoryCustomizer
- 6. Download Source Code
- 7. References
P.S Tested with Spring Boot 1, 2, and 3.
1. application.properties
If we have src/main/resources/application.properties
file, add or update the server.port
property.
server.port=8181
2. application.yml
If we have src/main/resources/application.yml
file, add or update the server.port
property.
server:
port: 8181
3. Command Line
Using the command line, we can change the port using the server.port
property as the command line argument.
java -jar spring-boot-hello-world-1.0.jar --server.port=8181
4. Environment Variable
We also can change the port using the environment variable SERVER_PORT
.
export SERVER_PORT=8181
java -jar spring-boot-hello-world-1.0.jar
5. WebServerFactoryCustomizer
We can implement WebServerFactoryCustomizer
to programmatically change the embedded servlet container port.
package com.mkyong.config;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomWebServerFactory implements
WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.setPort(8181);
}
}
Note
Since Spring Boot 2.0, the EmbeddedServletContainerCustomizer
is deprecated in favor of the WebServerFactoryCustomizer
interface.
6. Download Source Code
$ git clone https://github.com/mkyong/spring-boot.git
$ cd spring-boot-change-port
$ mvn spring-boot:run
Hi Myong,Your CustomContainer code worked..For a very long time I couldn’t get the solution of this..Thanks
Thanks for sharing it 🙂
thanks. very useful.