How to change running port in spring boot?

  • |
  • 07 August 2023
Post image

There are 3 ways to change default running port in spring boot application:

By default, the embedded server starts on port 8080.

1- Use Property files

This is the easiest and fastest way. For the server port we need to change property called server.port

For application.properties file:

server.port=9876
2023-08-07T13:12:17.244+03:00  INFO 24154 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9876 (http) with context path ''

For application.yml file:

server:
  port: 9876

You can even further specialized the running port for each environment. For instance if you want your application to run specific port in development, then update the application-dev.properties file:

server.port=9876

2- Programmatic Configuration

We can set the port in the main method as well:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Collections;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(DemoApplication.class);
		app.setDefaultProperties(Collections
				.singletonMap("server.port", "9876"));
		app.run(args);
	}
}

3- Using command line

After you create your jar file, you can specify the running port as well:

java -jar spring-application.jar --server.port=9876

You May Also Like