This post will discuss how to change the server port for a Spring Boot application to listens to HTTP requests.

By default, the embedded server of a Spring Boot application listens for HTTP requests on port 8080. If your application fails to start on port 8080, that means that port is already in use, and we would get a dedicated error message similar to the one shown below:

***************************
APPLICATION FAILED TO START
***************************

Description:

The embedded servlet container failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port.

We can resolve this issue by changing the port of our application. There are several ways to achieve this, as discussed below:

1. Property file

In Spring Boot, we can set the server port in application.properties located in /src/main/resources/ directory, as shown in the following example:

2. YAML file

We can also store external properties in a YAML file, which is a superset of JSON. Create a file named application.yml and put it in the root of the classpath. The preceding example corresponds to the following YAML file:

 
Both application.properties and application.yml can be placed in four pre-determined locations:

  1. root of the classpath
  2. current directory
  3. package /config in classpath
  4. /config subdirectory of the current directory

3. System property

We can also set server.port as System property inside the main method, as shown below:

4. Change VM Options

We can also define JVM system property while starting Spring Boot application through command line argument, as shown below:

 
Here, springBootApp.jar is our executable JAR. Otherwise, in IntelliJ IDEA, go to Run -> Edit Configurations -> VM options, and add the following argument to the VM

 
We can also pass server.port property as an application argument, as shown below:

5. Define OS environment variable

We can also use SERVER_PORT as an OS environment variable in Unix/windows. This works since Spring Boot uses some relaxed rules for binding Environment properties to @ConfigurationProperties beans.

 
1. Windows

 
2. UNIX

 
We can also configure the servlet container’s port programmatically:

1. Before Spring Boot 2, we can use the EmbeddedServletContainerCustomizer interface.

 
2. With Spring Boot 2, the EmbeddedServletContainerCustomizer interface is replaced by WebServerFactoryCustomizer,

 
Tips:

For completely turning off the HTTP endpoints, use server.port=-1. This would still create a WebApplicationContext and can be useful for testing.

To assign a random HTTP Port, use server.port=0. To discover the random HTTP port at runtime, use @Value("${local.server.port}").

That’s all about configuring a port in a Spring Boot application.