Spring Boot comes with a really easy way to manage spring applications with minimal setup involvement. Here I’ll explain how we can change the default port of the embedded tomcat server (8080) to any port you prefer in spring boot.
Changing Default Port Using Property File
Spring boot uses 8080 port by default when we initiate a new project. We can use server.port property inside src/main/resources/application.properties to change this default port to another port which we prefer.
server: port: 8089
Setup Environment Specific Ports Using Properties
Let’s assume we have a requirement on setting up different ports on different environments like below,
- 8081 – DEV
- 8082 – STAGING
- 8083 – PRODUCTION
So within the same application, we can have multiple property files for each environment to build this setup.
Then while you are running the application you could set whatever profile you needs to have, then spring boot will refer the given property file which has given profile name while running the application.
Running an application with dev profile just give following command,
with a gradle based project,
$ ./gradlew bootRun --args='--spring.profiles.active=dev'
or else with a maven based project use following command,
$ mvn spring-boot:run -Dspring-boot.run.profiles=dev
or else if you are running your jar build file then use following command,
$ java -jar app.jar -Dspring.profiles.active=dev
Using Command Line Argument
We can set server-port using a command line argument as we set the active profile while running the application.
There are two ways to do that, You can use either way to get done things the way you need.
Before running this argument you should have correctly built a jar file from your application.
$ java -jar my-app-1.0.0.jar --server.port=8081
$ java -jar -Dserver.port=8081 my-app-1.0.0.jar
Note on Configuration File Priority
As of now, you can understand multiple ways of injecting configuration into the spring boot application. But there is an order on how spring boot captures the configurations. That is,
- Embedded server config.
- Command Line arguments – ( -Dserver.port=8081 )
- Property files – ( application.properties )
- The configuration defined in @SpringBootApplication main class.
This is a really simple guide on how we can change the default port in the spring boot application while developing and deploying on multiple environments. Hope you got a good understanding of how we can set up ports and profiles to manage those inside a spring boot application.
If you are looking for spring boot based practical application development tutorials, just check our article series and comment on whatever new things you need to see on our website.