1. Introduction
In this quick tutorial, we’ll learn how to configure the server port for a Spring Boot application.
By default, Spring Boot applications run on port 8080. However, if multiple application instances run on the same machine, we may encounter port conflicts. Therefore, we need to be able to define a different port for each application.
Let’s begin.
2. Configuring the server.port
Properties File
The easiest way to change the default port is to configure the server.port
property in a properties file located in /src/main/resources/
. We can find this property in the application.properties
if the application uses the standard configuration:
server.port=8090
For example, above, we’ve set the port to 8090. So, now, every time we run the application, it will listen on port 8090.
The properties might not be available in our project if we’re using the YAML format. In this case, we can configure the port in the application.yml
file:
server:
port: 8090
3. Random Port Assignment
Another option is to assign a random port to the application. We can easily avoid port conflicts using this method. To do this, we set the server.port
property to 0:
server.port=0
Now, when we start the application, Spring Boot will dynamically assign an available port.
4. Command-Line Arguments
We might only sometimes want to define the port in the configuration files. Or, we could test the application on a different port. In this case, we can force the application port through command-line arguments:
java -jar yourapp.jar --server.port=8090
Additionally, we can set the port using the system properties as well:
java -Dserver.port=8090 -jar yourapp.jar
5. Conclusion
In this short article, we’ve configured the port for a Spring Boot Application. First, we configured the server.port
property in the application.properties
or application.yml
file. Then, we learned how to assign a random port to the application. Finally, we saw how to set the port using command-line arguments.
We can look for the complete code on Github