Spring boot provides provides default embedded server with spring-boot-starter-web dependency. This embedded server uses port 8080 by default.

We may want to change the default port of this server to run on different port. This makes the spring boot application to 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.

Change embedded server port spring boot

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

Using Configuration Files

We can update spring boot applications embedded server port by using 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 use command line arguments to change server port number. While starting spring boot application, we can pass server.port argument.

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

Changing server port programmatically

We can change the server port with programmatic customization. With spring boot 2, we can implement 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 this article, we learned different ways to change embedded server port number of spring boot application.

Happy coding 🙂 🙂

You may also interested in