spring boot

Change default port of spring boot application

Change spring boot embedded server port

Spring boot provides default embedded servers with the spring-boot-starter-web dependency. This embedded server uses port 8080 by default. We can easily change the port number of the spring boot application.

We may want to change the default port of this server to run on a different port. This makes the spring boot application listen on different ports.

This is very useful when we run different instances of a single spring boot application. This is also helpful when we want to run different services at a time with different port numbers.

We can achieve this with different methods. Below are a few of the methods, which we can use to change the server port number.

change port of spring boot app using the configuration files

We can update spring boot applications embedded server port by using the server.port property.

application.properties

server.port=8081

application.yml

server:
  port:8081

If we set the property server.port‘s value to 0, spring boot uses a random available port.

Using command line arguments

We can also use the command line arguments to change the server port numbers. While starting spring boot application, we can pass the server.port argument.

java -jar -Dserver.port=8081 myApp.jar

Change the spring boot server port programmatically

We can change the server port with programmatic customization. With spring boot 2, we can implement the WebServerFactoryCustomizer interface as given below.

@SpringBootApplication
public class SpringBootTestApplication implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootTestApplication.class, args);
	}

	@Override
	public void customize(ConfigurableServletWebServerFactory factory) {
		factory.setPort(9999);
	}
}

Conclusion

In conclusion, In this article, we learned different ways of changing the embedded server port number of the spring boot applications.