Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure server port when running jar

I currently working on an Spring Boot application written in Java 8 using Gradle. What I am looking for is to pass as an argument the server port when running the Jar from the command line.

For example:

  • java -jar myApplication.jar --port=8888: This runs my Spring boot application using port 8888
  • java -jar myApplication.jar: Since no port number is passed as argument, the spring boot application should run on a default port number (let's say 8080)

Can anyone help me with this ?

like image 733
T code Avatar asked Jan 17 '17 10:01

T code


People also ask

How do I run a spring boot program on a different port?

The fastest and easiest way to customize Spring Boot is by overriding the values of the default properties. For the server port, the property we want to change is server. port. By default, the embedded server starts on port 8080.


3 Answers

From Spring boot documentation, the command line is :

java -Dserver.port=8888 -jar myApplication.jar

You can also use Spring boot configuration file as described in the documentation.

like image 185
Mickael Avatar answered Oct 04 '22 18:10

Mickael


Caution Always pass the -D<key>=<value> JVM parameters before the -jar arguments otherwise it wouldn't accept your parameters and then it will run with default values. e.g:

Correct java command to execute the jar on a particular port is:

java -Dserver.port=8888 -jar target/my-application-jar-path.jar

The above command will run the JVM on the port 8888 but the below command

java -jar target/my-application-jar-path.jar -Dserver.port=8888

Will run on the port 8080, it will ignore the JVM parameters after -jar

Best practice in spring-boot application is to set the server.port into the application.properties file as:

server.port=9090

Or on the particular application-<ENV>.properties file with specific ENVIROMENT.

like image 32
krishna Prasad Avatar answered Oct 04 '22 18:10

krishna Prasad


For SpringBoot use:

 java -jar app.jar --server.port=9000

(taken from 2.1. Accessing Command Line Properties in the Spring documents)

like image 39
Tal Jacob - Sir Jacques Avatar answered Oct 04 '22 18:10

Tal Jacob - Sir Jacques