Spring boot change default port of embedded server

Lokesh Gupta

By default, Spring boot applications start with embedded tomcat server start at default port 8080. We can change default embedded server port to any other port, using any one of below technique.

TIP – 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 default server port from properties file

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

1.1. application.properties

server.port=9000

1.1. application.yml

server:
  port : 9000

2. Change the server port programatically

EmbeddedServletContainerCustomizer interface is used to customize embedded tomcat 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.

2.1. Spring boot2 – WebServerFactoryCustomizer interface

Change default server port in spring boot2 applications by implementing ConfigurableWebServerFactory interface.

@Component
public class AppContainerCustomizer 
			implements WebServerFactoryCustomizer< ConfigurableWebServerFactory > {
  
    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        factory.setPort(9000);
    }
}

2.2. Spring boot 1.x – EmbeddedServletContainerCustomizer interface

Change default server port in spring boot 1.x applications by implementing EmbeddedServletContainerCustomizer interface.

@Component
public class AppContainerCustomizer implements EmbeddedServletContainerCustomizer {

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {

		container.setPort(9000);
	}
}

3. Spring boot change default port from command line

If the application is built as uber jar, we may consider this option as well. In this technique, we will pass ‘server.port’ argument during application run command.

$ java -jar -Dserver.port=9000 spring-boot-demo.jar

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

Happy Learning !!

Comments

Subscribe
Notify of
guest
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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode