How can I configure port for a Spring Boot application?

January 04, 2020 No comments Port Spring Boot Configuration

1. Default Spring Boot port

Spring Boot gives reasonable defaults for its configuration attributes, but also gives the ability to provide custom properties that will suit our needs. By default Spring Boot starts on the port 8080 and we have several options to change that port.

1.1. Configuration file

In order to change starting port from 8080 to 8888 we can override server.port property in configuration with value 8888.

  • for we will need to add the following line:

  • for application.yml

      port: 8888

Both and application.yml files are recognized by Spring Boot automatically when they are located in src/main/resources path.

1.2. System property

Changing Spring Boot port can be also achieved by setting an environment variable SERVER_PORT on the operating system where the server will be started.

  • to set an environment variable on Linux use export command:
    export SERVER_PORT=8888
  • to set an environment variable on Windows use setx command:
    setx SERVER_PORT 8888

1.3. Programmatic Configuration

We can change the port programmatically by:

  • setting the particular property when starting the application
package com.frontbackend;

import java.util.Collections;

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

public class Application {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.setDefaultProperties(Collections.singletonMap("server.port", "8888"));;
  • customizing the embedded server configuration
package com.frontbackend;

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

public class ServerPortCustomizer
        implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {

    public void customize(ConfigurableWebServerFactory factory) {

1.4. Using a Random Port

Sometimes there is a need to run Spring Boot on a first random available port. To do so you simply have to set server.port=0. Spring Boot prevent clashed using OS natives so don't worry that port will be taken.

{{ message }}

{{ 'Comments are closed.' | trans }}