Skip to content

How To Configure Port For a Spring Boot Application

There are four ways to configure your port for a spring boot application: configuration files, the command line, a Java system property, and your spring boot application.

Gopi Gorantala
Gopi Gorantala
1 min read

Table of Contents

Configuring a port for a Spring Boot application is straightforward. By default, Spring Boot runs on port 8080. However, you can change this by modifying the application’s configuration file or setting a command-line argument.

There are various methods to configure the port

Configuration files

application.properties

Open the src/main/resources/application.properties file and add the following line to specify the desired port:

server.port=8081

Replace 8081 with the port number you want.

application.yml

Open the src/main/resources/application.yml file and add the following lines:

server:
  port: 8081

Replace 8081 with your desired port.

Command-Line Arguments

You can override the port by passing it as a command-line argument when starting the application:

java -jar your-app.jar --server.port=8081

Java System Property

You can also specify the port as a system property when running the application:

java -Dserver.port=8081 -jar your-app.jar

This option is not recommended, but occasionally developers/companies prefer to do it this way.

Programmatically, in your Spring Boot Application

You can also configure the port programmatically in your Spring Boot application by setting it in the SpringApplication class:

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

@SpringBootApplication
public class Application {

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

This will set the port to 8081.

Choose the method that best fits your needs. The configuration in application.properties or application.yml is the most common approach for production applications.

Spring Issues

Gopi Gorantala Twitter

Gopi is a software engineer with over 14 years of experience. He specializes in Java-based technology stack and has worked for various startups, the European government, and technology giants.

Comments