How to configure port for a Spring Boot application
To configure the Spring Boot server port, server.port
can be set in application.properties
/application.yml
or specified as a command-line argument:
Properties file:
server.port=8081
YAML file:
Command-line:
java -jar app.jar --server.port=8081
Simply replace 8081
with your desired port number.
Setting up dynamic ports
During integration testing, there may be the need for random port allocation to avoid conflicts. By assigning 0
to server.port
:
Spring Boot will automatically choose an available port at startup.
Various methods to configure the port
In diverse development and deployment environments, you have several ways of configuring the port:
Command-line overrides
The command-line method is highly prioritised. Use -D
to set system properties:
Through your IDE
In your IDE's run/debug configurations, specify application arguments directly:
Using environment variables
For dockerized systems or similar environments, you can use the system environment variables, such as:
Spring Boot's relaxed binding rules convert SERVER_PORT
into server.port
.
Programmatically setting the port
In Spring Boot 2.x, to set the port programmatically, use WebServerFactoryCustomizer
:
For older Spring Boot versions, EmbeddedServletContainerCustomizer
offers similar functionality.
Using Maven or Gradle
For Maven or Gradle users, you can configure your port as part of the build process:
Maven:
Gradle:
An external configuration directory
Place application.properties
or .yml
in a ./config/
directory outside your jar to override port settings:
Dynamic environment configuration
Elastic cloud environments or container orchestration systems like Kubernetes might need dynamic configuration. Fortunately, Spring profiles and service discovery tools can manage these requirements.
Mind the troubleshooting and best practices
Configuring your port in Spring Boot is indeed fun, but few things you need to look out for to avoid walking into trap doors:
Watch for port conflicts
Ensure your chosen port isn't already taken. Use server.port=0
for a random available port.
Check for firewall restrictions
The firewall might be the doorkeeper to your port, so be sure to cross-check firewall rules to avoid blocked port access.
Use secure ports for HTTPS
Choose port 443
for HTTPS connections. Just be sure to have your SSL keys and certificates ready for the formal party!
Load balancers and proxies
If your application runs behind a load balancer or reverse proxy, configure properly to ensure the right port is exposed neatly.
Was this article helpful?