Spring Boot: Change Default Port of Embedded Server

By default, Spring boot embedded server starts at port 8080. Learn to change the default port using Java configuration, command line, and properties.

spring boot logo

By default, Spring boot applications start with an embedded Tomcat server at the default port 8080. We can change the default embedded server port to any other port number, using any one of the several techniques such as:

  • Embedded server configuration
  • Command-line arguments
  • Properties file

When defined in multiple places, it is also the order of priority.

To scan for a free port (using OS natives to prevent clashes), use ‘server.port=0‘. Now Spring boot will find any unassigned HTTP port for us.

1. Change Port Programmatically

The WebServerFactoryCustomizer interface is used to customize the embedded server configuration. Any beans of this type will get a callback with the container factory before the container itself is started, so we can set the port, address, error pages etc.


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);
  }
}

2. Change Port from Command Line

We can also pass the port number as a command line argument:

java -jar your-app.jar --server.port=8081

3. Change Port using Properties

We can do lots of wonderful things by simply making a few entries in the application.properties file in any spring boot application. Changing the server port is one of them.

The following property server.port will start the server in port 9000.

server.port=9000

The equivalent YAML configuration is:

server:
  port : 9000

Let me know if you know any other way to accomplish to change the spring boot embedded server default port.

Happy Learning !!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.