Change Server Port in Spring Boot

1. Overview

Typically, the Spring Boot apps run on the port 8080. However, in some cases we may need to run the apps on other ports. We can change the server port easily in Spring Boot.

2. Using Properties

Let’s change the server port using server.port property in our application properties:

server.port = 9000

In case, we are using yml, then we can change the port in application.yml properties file using server port property:

server:
  port: 9001

3. Using Command Line

We can also configure the port while launching the app. In this case, we don’t need to modify the application properties or the code.

Now, let’s provide the server port while launching the application using the cmd:

java -Dserver.port=9001 -jar SpringBootDemo.jar

Or, we can pass server port as an argument to the Spring boot application:

java -jar SpringBootDemo.jar –-server.port=9001

4. Changing Port Programmatically

Now, let’s change the server port programmatically by extending WebServerFactoryCustomizer interface:

@Component
public class ServerCustomization implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory > {

	public void customize(ConfigurableServletWebServerFactory server) {
		server.setPort(9002);
	}
}

5. Conclusion

In this article, we discussed various options to change the server port for Spring Boot apps.

As always the code for all these examples is available on GitHub.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s