Main Tutorials

How to change the default port in Spring Boot

change 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

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.

application.properties

  server.port=8181

2. application.yml

If we have src/main/resources/application.yml file, add or update the server.port property.

application.yml

  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.

Terminal

  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.

Terminal

  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.

CustomWebServerFactory.java

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

7. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Priyo
6 years ago

Hi Myong,Your CustomContainer code worked..For a very long time I couldn’t get the solution of this..Thanks

Gaurav Bhandari
3 years ago

Thanks for sharing it 🙂

Madhu
3 years ago

thanks. very useful.