Spring boot change default port of embedded server

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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Spring boot change default port of embedded server”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.