This article will guide you to change the default port of your embedded server in SpringBoot applications.

As you alredy know that spring Boot application comes with an embedded server and by default, you can run your applications without installing any external server. If you run it, by default it will be at port 8080.

If you want to change the default port of Embedded server in Spring Boot then follow the below process.

Using property file configuration :

find the application.properties file (or application.yml for YAML configuration)

 add server.port=XXXX (replace XXXX with your desired port number) in application.properties.

or below code in application.yml

server:
  port: 8090

You can maintain different ports for environments. Let’s take a simple scenario, application to be run on 8082 for dev environment and 8089 for prod environment. By using spring profiles we can achieve this. In this scenario you have to create 2 property files one for dev and other prod.

application-dev.yml

server:
  port: 8082

application-prod.yml

server:
  port: 8089

Run your application with spring.active.profile vm agrument.

//in dev 
java -jar -Dspring.profiles.active=dev your-application.jar 

//in prod
java -jar -Dspring.profiles.active=prod your-application.jar 
Using CommandLine :

To change the port of a Spring Boot application via the command line, you can use the following command.

java -jar -Dserver.port=XXXX your-application.jar

Replace XXXX with your desired port number.

Programmatically:

You can also customize embedded server port programmatically by using WebServerFactoryCustomizer functional interface. You have to override void customize(T factory) method. Following code will be able to help you on this.

@Component
public class ServerPortCustomizer 
  implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
 
    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        factory.setPort(8086);
    }
}

Also Read :

How to Create a SpringBoot project

commonly used Annotations in SpringBoot