1046

How do I configure the TCP/IP port listened on by a Spring Boot application, so it does not use the default port of 8080.

Tung
  • 1,579
  • 4
  • 15
  • 32
Paul Verest
  • 60,022
  • 51
  • 208
  • 332
  • 11
    If someone interested, here is shown how to have multiple ports - https://stackoverflow.com/questions/36357135/configure-spring-boot-with-two-ports – Betlista Feb 08 '18 at 13:21
  • if you use "yml" file for configuration then you can use this server: port: 8081 Also annotate you main class as "@SpringBootApplication" and remove @ EnableAutoConfiguration – Keaz Jun 23 '18 at 07:52
  • your project [application.properties] for add the server.port=8080 – Lahiru Samishka Oct 08 '19 at 11:07
  • set `server.port=8080` in application properties. this configuration is in `ServerProperties.class` class under `org.springframework.boot.autoconfigure.web`. – Atif Mar 11 '20 at 10:12

62 Answers62

1545

As said in docs either set server.port as system property using command line option to jvm -Dserver.port=8090 or add application.properties in /src/main/resources/ with

server.port=8090

For a random port use:

server.port=0

Similarly add application.yml in /src/main/resources/ with:

server:
  port: 8090
blacktide
  • 10,654
  • 8
  • 33
  • 53
Paul Verest
  • 60,022
  • 51
  • 208
  • 332
  • 75
    When random port is used, port info can get with `@Value("${local.server.port}")` – azizunsal Jul 23 '15 at 12:46
  • 52
    Actually command line option is --server.port=8090 not -Dserver.port=8090. http://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html#howto-use-short-command-line-arguments – alpert Aug 19 '15 at 06:39
  • 1
    As a compliment to this answer: According to the [spring docs](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-application-property-files) there are other paths you can put `application.properties` on. In my case that helped a lot. – sargas Oct 02 '15 at 19:37
  • 17
    -Dserver.port=XXXX did not work for me. I used OS environment variable mode: `$ SERVER_PORT=8090 java -jar ` – Soumya Kanti Oct 08 '15 at 07:38
  • It is also worth noting that once you so this it will only matter locally. Once you deploy this application on a server `server.port = 8080 will be ignored. – Mike3355 Apr 26 '16 at 17:28
  • `java -jar --server.port=8090` works in spring 1.4.0 – rzymek Sep 13 '16 at 20:15
  • 16
    Both (1) `java -Dserver.port=XXXX -jar ` and (2) `java -jar --server.port=YYYY` works. The first command defines `server.port` system property, and the second command pass the property through the command line arguments (`String... args` in the `main` method). Moreover, if you run with `java -Dserver.port=XXXX -jar --server.port=YYYY`, `YYYY` takes precedence over `XXXX`, this is why Spring Boot Externalized Configuration is so charming. – tan9 Nov 29 '16 at 16:28
  • Many ways to change port on Spring Boot tomcat http://javabycode.com/spring-framework-tutorial/spring-boot-tutorial/spring-boot-change-tomcat-port-command-line.html – David Pham Nov 16 '17 at 09:48
  • src/resources/application.properties server.port=8080 or – Yogesh Borkhade Jan 19 '18 at 09:43
  • You can set the server.port property in many different ways. Look at the configuration-documentation for spring boot and find the solution that suits you: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html – jorgen.ringen Jan 28 '18 at 17:41
  • In case you prefer maven, do this `mvn spring-boot:run -Dserver.port=8888` – old-monk Apr 12 '18 at 15:37
  • application.yaml can also be used instead of properties. – chethu Mar 09 '19 at 15:26
  • -Dserver.port did not work but --server.port worked. Also it should be passed to java -jar command and not mvn. So for example after building the projekt using mvn you execute java -jar artifact.jar --server.port=9099 to run the server on another to port – velocity Sep 03 '20 at 12:26
  • This does not work – Philip Rego Dec 10 '21 at 16:07
  • There is nice explanation of ways to change port of spring boot https://www.javavogue.com/2019/02/how-to-change-the-default-port-in-spring-boot/ – Anuj Dhiman Jan 08 '22 at 09:19
  • Also you can set the management port to expose the actuator on different port – amir bayan Dec 08 '22 at 21:15
  • I had to rebuild the jar to get this to work, by the way – Seth Faulkner Mar 28 '23 at 12:56
267

There are two main ways to change the port in the Embedded Tomcat in a Spring Boot Application.

Modify application.properties

First you can try the application.properties file in the /resources folder:

server.port = 8090

application.properties file

Modify a VM option

The second way, if you want to avoid modifying any files and checking in something that you only need on your local, you can use a vm arg:

Go to Run -> Edit Configurations -> VM options

-Dserver.port=8090

Change port with a vm arg

Additionally, if you need more information you can view the following blog post here: Changing the port on a Spring Boot Application

anataliocs
  • 10,427
  • 6
  • 56
  • 72
  • In STS 4 it is at run -> run configurations -> main, then scroll down to Table with Parameter Name and Value – serv-inc Apr 28 '19 at 13:00
208

Since Spring Boot provides various configuration externalization mechanism (through various PropertySource implementations and/or processors wired into Environment object in order), you can set any property outside of your jar archive through following methods:

  1. Pass property through command line argument as application argument

    java -jar <path/to/my/jar> --server.port=7788
    
  2. From property in SPRING_APPLICATION_JSON (Spring Boot 1.3.0+)

    • Define environment variable in U*IX shell:

      SPRING_APPLICATION_JSON='{"server.port":7788}' java -jar <path/to/my/jar>
      
    • By using Java system property:

      java -Dspring.application.json='{"server.port":7788}' -jar <path/to/my/jar>
      
    • Pass through command line argument:

      java -jar <path/to/my/jar> --spring.application.json='{"server.port":7788}'
      
  3. Define JVM system property

    java -Dserver.port=7788 -jar <path/to/my/jar>
    
  4. Define OS environment variable

    • U*IX Shell

      SERVER_PORT=7788 java -jar <path/to/my/jar>
      
    • Windows

      SET SERVER_PORT=7788
      java -jar <path/to/my/jar>
      
  5. Place property in ./config/application.properties configuration file

    server.port=7788
    

    and run:

     java -jar <path/to/my/jar>
    
  6. Place property in ./config/application.yaml

    server:
        port: 7788
    

    and run:

     java -jar <path/to/my/jar>
    
  7. Place property in ./application.properties

    server.port=7788
    

    and run:

     java -jar <path/to/my/jar>
    
  8. Place property in ./application.yaml

    server:
        port: 7788
    

    and run:

     java -jar <path/to/my/jar>
    

You can combine above methods all together, and the former configuration in the list take precedence over the latter one.

For example:

SERVER_PORT=2266 java -Dserver.port=5566 -jar <path/to/my/jar> --server.port=7788

The server will start and listen on port 7788.

This is very useful providing default properties in PropertySources with lower precedence (and usually packaged in the archive or coded in the source), and then override it in the runtime environment. And it is the design philosophy of Spring Boot:

Be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.


SERVER_NAME to server.name conversion was done by Relaxed Binding.

tan9
  • 3,490
  • 2
  • 18
  • 21
138

Also, you can configure the port programmatically.

For Spring Boot 2.x.x:

@Configuration
public class CustomContainer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
  public void customize(ConfigurableServletWebServerFactory factory){
    factory.setPort(8042);
  }
}

For older versions:

@Configuration
public class ServletConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            container.setPort(8012);
        });
    }
}
Positive Navid
  • 2,481
  • 2
  • 27
  • 41
makerj
  • 2,179
  • 2
  • 18
  • 27
  • 2
    This is working and very useful, when you have port in your own config file and want to set it during runtime. – Xdg Nov 08 '15 at 09:48
  • 6
    This was helpful when i needed to deploy an application to a AWS Elastic Beanstalk service, to get the port from an environment variable. – Martin Hansen Nov 19 '15 at 12:51
  • This is super useful when all you want is a self-contained unit or integration test, +1. – Priidu Neemre Apr 28 '16 at 10:34
  • Very useful when the env variable for port is already defined under a different name. – higuaro Aug 18 '16 at 08:27
  • 2
    Is'nt it the `@Configuration` instead of `@Controller`? Please update if so. – Lucky Sep 13 '16 at 11:52
  • It should be `@Configuration`, but if you import it using `@Import` it works, not sure if it is working with auto configuration search. – kap Mar 23 '17 at 13:00
  • For a beginner: I tried creating a file `PortConfiguration.java` in the package folder and pasted this code here. However, I'm geting an error from VS code: Configuration cannot be resolved to a type. Any suggestions? – PeMa Mar 02 '18 at 07:12
  • interesting, I didn't know that it is possible to do it programmatically. Thanks for info – Heybat Dec 17 '20 at 23:24
108

If you would like to run it locally, use this -

mvn spring-boot:run -Drun.jvmArguments='-Dserver.port=8085'

As of Spring Boot 2.0, here's the command that works:

mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085

clues were at:

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
itwarilal
  • 1,314
  • 1
  • 10
  • 17
97

You can set port in java code:

HashMap<String, Object> props = new HashMap<>();
props.put("server.port", 9999);

new SpringApplicationBuilder()
    .sources(SampleController.class)                
    .properties(props)
    .run(args);

Or in application.yml:

server:
    port: 9999

Or in application.properties:

server.port=9999

Or as a command line parameter:

-Dserver.port=9999
ayurchuk
  • 1,879
  • 1
  • 17
  • 13
  • Using the HashMap will work only if no port is set in applications.properties or .yml. – Milgo Apr 25 '19 at 11:28
  • I have a 2nd "application" class as a utility, and I wanted to only set a different port in that one. Therefore all the config file based approaches were not helpful for me. Close to giving up I found your programatic approach. Thank you! – Thomas Schütt Oct 08 '21 at 12:43
62

In case you are using application.yml add the Following lines to it

server:
     port: 9000

and of course 0 for random port.

Paul Verest
  • 60,022
  • 51
  • 208
  • 332
gatolgaj
  • 1,193
  • 7
  • 12
53

As explained in Spring documentation, there are several ways to do that:

Either you set the port in the command line (for example 8888)

-Dserver.port=8888 or --server.port=8888

Example : java -jar -Dserver.port=8888 test.jar

Or you set the port in the application.properties

server.port=${port:4588}

or (in application.yml with yaml syntax)

server:
   port: ${port:4588}

If the port passed by -Dport (or -Dserver.port) is set in command line then this port will be taken into account. If not, then the port will be 4588 by default.

If you want to enforce the port in properties file whatever the environment variable, you just have to write:

server.port=8888
OlivierTerrien
  • 2,451
  • 1
  • 19
  • 31
43

Include below property in application.properties

server.port=8080
Derrick
  • 3,669
  • 5
  • 35
  • 50
Chandramouli
  • 552
  • 4
  • 6
  • This doesn't work. What application.properties? Which properties can overwrite this one? How can I be sure Spring is picking it up? – Philip Rego Dec 10 '21 at 16:24
30

When you need a programatically way of doing it, you can set it during startup:

System.getProperties().put( "server.port", 80 );
SpringApplication.run(App.class, args);

This might help for things like environment dependent port. Have a nice day

Luis Mauricio
  • 397
  • 3
  • 6
21

if you are using gradle as the build tool, you can set the server port in your application.yml file as:

server:
  port: 8291

If you are using maven then the port can be set in your application.properties file as:

server.port: 8291
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
VSharma
  • 471
  • 4
  • 8
20

To extend other answers:

There is a section in the docs for testing which explains how to configure the port on integration tests:


At integration tests, the port configuration is made using the annotation @SpringBootTest and the webEnvironment values.


Random port:

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

You can inject the value using @LocalServerPort which is the same as @Value("${local.server.port}").

  • Example:

Random port test configuration:

@RunWith(SpringRunner.class
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ExampleTest {
   ...
   @LocalServerPort //to inject port value
   int port;
}

Defined port:

@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)

It takes the value from server.port if is defined.

  • If is defined using @TestPropertySource(properties = "server.port=9192"), it overrides other defined values.
  • If not, it takes the value from src/test/resources/application.properties (if exists).
  • And finally, if it is not defined it starts with the default 8080.

Example:

Defined port test configuration:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource(properties = "server.port=9192")
public class DemoApplicationTests {

    @Test
    public void contextLoads() {
    }

}
andi
  • 981
  • 2
  • 11
  • 18
Pau
  • 14,917
  • 14
  • 67
  • 94
19

You can specify port by overriding EmbeddedServletContainerFactory bean within your configuration (java based or xml). There you can specify port for used embedded servlet container. Please, see Spring Boot - Core "Embedded Servlet Container Support" paragraph and example there. Hope this helps.

Will
  • 6,561
  • 3
  • 30
  • 41
nndru
  • 2,057
  • 21
  • 16
  • 1
    Direct link: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-configure-tomcat – Erik Martino Nov 13 '14 at 10:24
  • Here's a current link to the programmatic override section: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-customizing-embedded-containers – jocull Jun 14 '18 at 15:33
19

In application.properties file present in resources:

server.port=8082
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25
19

There are three ways to do it depending on the application configuration file you are using

a) If you are using application.properties file set

server.port = 8090

b) If you are using application.yml file set server port property in YAML format as given below

server:
     port: 8090

c) You can also Set the property as the System property in the main method

System.setProperty("server.port","8090");
LukeSolar
  • 3,795
  • 4
  • 32
  • 39
Praneeth
  • 529
  • 5
  • 8
15

Add this in your application.properties file

server.port= 8080
Derrick
  • 3,669
  • 5
  • 35
  • 50
Sridhar Battala
  • 159
  • 1
  • 3
15

There are many other stuffs you can alter in server configuration by changing application.properties. Like session time out, address and port etc. Refer below post

ref: http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html

I used few of them as below.

server.session.timeout=1
server.port = 3029
server.address= deepesh
Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29
14
  1. As everyone said, you can specify in application.properties
    server.port = 9000 (could be any other value)

  2. If you are using spring actuator in your project, by default it points to
    8080, and if you want to change it, then in application.properties mention
    management.port = 9001 (could be any other value)

Rakesh
  • 1,374
  • 1
  • 16
  • 24
14

In the application.properties file, add this line:

server.port = 65535

where to place that fie:

24.3 Application Property Files

SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:

A /config subdirectory of the current directory
The current directory
A classpath /config package
The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).

In my case I put it in the directory where the jar file stands.

From:

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-application-property-files

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
14

By default spring boot app start with embedded tomcat server start at default port 8080. spring provides you with following different customization you can choose one of them.

NOTE – you can use server.port=0 spring boot will find any unassigned http random port for us.

1) application.properties

server.port=2020

2) application.yml

server:  
     port : 2020

3) Change the server port programatically

3.1) By implementing WebServerFactoryCustomizer interface - Spring 2.x

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        // customize the factory here
        factory.setPort(2020);
    }
}

3.2) By Implementing EmbeddedServletContainerCustomizer interface - Spring 1.x

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        // customize here
        container.setPort(2020);
    }
}

4) By using command line option

 java -jar spring-boot-app.jar -Dserver.port=2020
anandchaugule
  • 901
  • 12
  • 20
12

Indeed, the easiest way is to set the server.port property.

If you are using STS as IDE, from version 3.6.7 you actually have Spring Properties Editor for opening the properties file.

This editor provides autocomplete for all Spring Boot properties. If you write port and hit CTRL + SPACE, server.port will be the first option.

Adrian Cosma
  • 467
  • 8
  • 10
12

By default, spring-web module provides an embedded tomcat server that is running under the port number 8080. If you need to change the port number of the application then go to application.properties file and configure the port number by using server.port property.

  server.port= 9876

then your application is running under the port 9876.

Nafaz M N M
  • 1,558
  • 2
  • 27
  • 41
11

Using property server.port=8080 for instance like mentioned in other answers is definitely a way to go. Just wanted to mention that you could also expose an environment property:

SERVER_PORT=8080

Since spring boot is able to replace "." for "_" and lower to UPPER case for environment variables in recent versions. This is specially useful in containers where all you gotta do is define that environment variable without adding/editing application.properties or passing system properties through command line (i.e -Dserver.port=$PORT)

Derrick
  • 3,669
  • 5
  • 35
  • 50
Ulises
  • 9,115
  • 2
  • 30
  • 27
11

Hope this one help

application.properties=> 

server.port=8090

application.yml=> 

server
  port:8090
9

You can add the port in below methods.

  1. Run -> Configurations section

  2. In application.xml add server.port=XXXX

Bogdan Bogdanov
  • 1,707
  • 2
  • 20
  • 31
gkarthiks
  • 471
  • 6
  • 17
9

Just have a application.properties in src/main/resources of the project and give there

server.port=****

where **** refers to the port number.

gawi
  • 2,843
  • 4
  • 29
  • 44
Shubham Khurana
  • 131
  • 1
  • 4
9

1.1 Update via a properties file.

/src/main/resources/application.properties

server.port=8888

Update via a yaml file.

   server:

     port: 8888

EmbeddedServletContainerCustomizer

@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {

        container.setPort(8888);

    }

}
Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
Buddhika Lakshan
  • 182
  • 2
  • 13
9

Providing the port number in application.properties file will resolve the issue

 server.port = 8080

"port depends on your choice, where you want to host the application"

Ashwini
  • 771
  • 10
  • 5
8

By Default Spring-web module provides an embedded tomcat server runs on port number 8080.

You can change it as follows -

A) If you are using gradle then use can set the property in your application.yml :

 server:  
      port: 8042

B) If you are using maven then you can set the property in your application.properties :

server.port: 8042

C) When you have port in your own config file and want to set it during runtime.

 By implementing WebServerFactoryCustomizer interface - Spring 2.x

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        // customize the factory here
        factory.setPort(8042);
    }
}

 By Implementing EmbeddedServletContainerCustomizer interface - Spring 1.x

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        // customize here
        container.setPort(8042);
    }
}
Ishan Garg
  • 571
  • 5
  • 13
7

You can also use SERVER_PORT environment variable to configure Spring Boot port. Just set the environment variable and restart the app:

set SERVER_PORT=9999 // on windows machine
export SERVER_PORT=9999 // on linux

Please note that if you do not set those environment variables system wide, you should run the boot app on the same session.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
7

You can set that in application.properties under /src/main/resources/

server.port = 8090
Abhijeet Ahuja
  • 5,596
  • 5
  • 42
  • 50
7

Mostly springboot runs on port:8080 because of embedded Tomcat. In some it may throw an error port 8080 already in use. To avoid this kind of issues we can config the server port.

Using application.properties

add server.port=9898

On runtime config

run your application with below arguments.

spring-boot:run -Drun.jvmArguments='-Dserver.port=8081'

Mohanraj
  • 396
  • 3
  • 8
  • 21
  • 1
    This answer is outdated. You need to use the following arguments `mvn spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8081'` , see https://stackoverflow.com/a/66370832/179014 – asmaier Nov 25 '22 at 13:43
  • I've confirmed it works in SB 3.1.1 - BTW is not necessary use `''`, therefore is `mvn spring-boot:run -Dspring-boot.run.jvmArguments=-Dserver.port=8081` works – Manuel Jordan Jul 16 '23 at 16:24
6

Using mvn shell command line, spring-boot 2:

mvn spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8085'
Ady Junior
  • 1,040
  • 2
  • 10
  • 18
5

You can configure your port in application.properties file in the resources folder of your spring boot project.

server.port="port which you need"
Derrick
  • 3,669
  • 5
  • 35
  • 50
Automator1992
  • 116
  • 1
  • 3
5

Running by Gradle:

  • Run in default port(8080): ./gradlew bootRun
  • Run in provided port(8888): ./gradlew bootRun --args='--server.port=8888'
  • If we have any variable in the application.properties file named PORT, run this: PORT=8888 ./gradlew bootRun

Running by Maven:

  • Run in default port(8080): mvnw spring-boot:run
  • Run in provided port(8888): mvnw spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8085'
  • Run in provided port(8888): mvn spring-boot:run -Dspring-boot.run.arguments='--server.port=8085'
  • Run in provided port(8888) with other custom property: mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8899 --your.custom.property=custom"
  • If we have any variable in the application.properties file named PORT, run this: SERVER_PORT=9093 mvn spring-boot:run

Using java -jar:

  • Create the .jar file:
    • For Gradle: ./gradlew clean build. We will find the jar file inside: build/libs/ folder.
    • For Maven: mvn clean install. We will find the jar file inside:target folder.
  • Run in default port(8080): java -jar myApplication. jar
  • Run in provided port(8888): java -jar myApplication.jar --port=8888
  • Run in provided port(8888): java -jar -Dserver.port=8888 myApplication.jar
  • Run in provided port(8888) having variable SERVER_PORT in application.properties file: SERVER_PORT=8888 java -jar target/myApplication.jar
Vadiraj Purohit
  • 898
  • 8
  • 20
Md. Shahariar Hossen
  • 1,367
  • 10
  • 11
5

Open the application.properties file in your spring boot application. And add the below property in the properties file.

server.port = 1443

This will be working fine and you can set any port number as per your wish.

kehsihba19
  • 83
  • 6
Santil
  • 124
  • 1
  • 4
4

"server.port=8080" will only works if your running application as a jar through main method,

This configuration will not work if your running this application as a war file through tomcat container.

4

If you are going to run apps as jar file in command environment, just type "SERVER_PORT=*** " as prefix. The full command to execute will look like below:

SERVER_PORT=8080 java -jar ***.jar

If you wanna run app in background in Linux, command with 'nohup' will look like below:

SERVER_PORT=8080 nohup java -jar ***.jar &
Rong.l
  • 338
  • 2
  • 13
4

There are three ways to do it

1 Set server.port property in application.properties file

server.port = 8090

2 Set server port property in application.yml file

server:
     port: 8090

3 Set the property as system property in main method

System.setProperty("server.port","8090");
Derrick
  • 3,669
  • 5
  • 35
  • 50
4

Just set the environment variable SERVER_PORT.
(The examples works on Linux)

  • Start via java -jar:
    SERVER_PORT=9093 java -jar target/eric-sc-dummy.jar

  • Start via maven spring-boot plugin:
    SERVER_PORT=9093 mvn spring-boot:run

Tips:

  • If you add other sub commands before the java -jar or mvn command, then you need to add export to set env in a separate command, and split them via ;, to make sure it's available to sub process.
    e.g:
    export SERVER_PORT=9093; export MAVEN_OPTS="-Xmx256m -Xms64m"; mvn spring-boot:run
Eric
  • 22,183
  • 20
  • 145
  • 196
4

You can configure the port in the application.property file or application.yaml file which is in src/main/resources .

server.port=8080

enter image description here

3

Apart from all the answers, I would like to point out that most IDE (IntelliJ with Spring plugin, STS) have a feature where it suggests all the configuration keys supported by SpringBoot. (i.e. all the opinionated configuration keywords)

enter image description here

Spring Plugin for Intellij

Sudip Bhandari
  • 2,165
  • 1
  • 27
  • 26
3

Server port declare in two types

1.static type

   server.port=8080. // your port number
  1. Dynamic type

     server.port=0.      // randomly generate port number. 
     server.port=${PORT:0}
    
SCouto
  • 7,808
  • 5
  • 32
  • 49
Pandiyan MCA
  • 41
  • 1
  • 7
3

Via

application.properties

server.port = 8082 (or any new port number)

via

application.yml

server
  port: 8082
Akash Verma
  • 638
  • 1
  • 11
  • 15
2

The default port is : 8080 but we can customize the port number in application.properties as shown below

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
server.port = 5050 -- #here we can give any port number.
Lova Chittumuri
  • 2,994
  • 1
  • 30
  • 33
2

This question is the first result if you google for Gradle Spring Port.

If you use gradle you can do something like this if you have the Spring Boot Gradle Plugin already applied:

bootRun {
    args += ["--server.port=[PORT]"]
}

For a more sophisticated answer please see my answer here.

Maurice Müller
  • 1,312
  • 3
  • 16
  • 32
2

If you are working over boot projects and you wanna configure the port you can give the input in the application.properties file like NOTE:properties file should be under src/main/resource

Spring properties

server.port=9999 If you using the CMD then follow this command -Dserver.port=9999 For default port its server.port=0 Make sure no port is using this port number

Community
  • 1
  • 1
Saravanan
  • 10
  • 1
  • 5
2

Similar to https://stackoverflow.com/a/36865796/1587329 and https://stackoverflow.com/a/40799750/1587329, a gradle one-liner would be

SERVER_PORT=9090 gradle bootRun
serv-inc
  • 35,772
  • 9
  • 166
  • 188
2

In Application properties just add 1 line

server.port = 8090
Joyson Rego
  • 968
  • 2
  • 11
  • 29
2

Programmatically, with spring boot 2.1.5:

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory server) {
        server.setPort(9000);
    }

}
Niel de Wet
  • 7,806
  • 9
  • 63
  • 100
1

This worked for me :

Added a custom container class :

@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
       configurableEmbeddedServletContainer.setPort(8888);
    }

}

But this was still not using port 8888.

Then I set "scanBasePackages" property like this on "@SpringBootApplication" class on my main method: (scanBasePackages = {"custom container package"})

@SpringBootApplication(scanBasePackages = {"com.javabrains.util"})
public class CourseApiApp {

    public static void main (String args []) {
        SpringApplication.run(CourseApiApp.class, args);
    }
}

And it started picking up port set in Custom Container.

S'chn T'gai Spock
  • 1,203
  • 18
  • 16
1

In spring boot you can easily configure the service exposing port in application.properties file.

server.port=portnumber

if you don't set a port specifically, then it will try to open the service with port 80. in case if it is already used, service will not be started on the embedded container.

Derrick
  • 3,669
  • 5
  • 35
  • 50
Anushka Ekanayake
  • 977
  • 2
  • 13
  • 33
1

if your port number can be random you can use random function in your application.properties server.port=${random.int(4)}

Devilluminati
  • 328
  • 1
  • 15
1

server.port = 0 for random port

server.port = 8080 for custom 8080 port

Jijo
  • 107
  • 1
  • 1
  • 10
1

in the file application.properties add the following: server.port=8888 THE PROT NEEDED ALWAYS MENTIONED HERE

Hilal Aissani
  • 709
  • 8
  • 3
1

Aside from adding the port on application.properties, you can also easily achieve multiple ports for different environments, by combining the property files approach with Spring profiles. Specifically, we can create a property file for each environment.

For example, we'll have an application-dev.properties file with this content:

server.port=8081

Then you can add another application-qa.properties file with a different port:

server.port=8082
Joel Wembo
  • 814
  • 6
  • 10
0

Configure the port details in Config file or application properties.

e.g.

port =8876
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
suveer
  • 35
  • 1
  • 5
0

put this code in u applicatop.properties file
enter image description here

BRAIEK AYEMN
  • 89
  • 1
  • 6
0

If you are use the spring command line interface (CLI) use the -- to separate commands from the spring command arguments, to change the port:

spring run hello.groovy -- --server.port=9000

spring-boot cli

Maske
  • 824
  • 2
  • 17
  • 35
0

Many parameters including server port can be changed in multiple ways. However there is an order of precedence as outlined below:

  1. First precedence is assigned to custom code like below:
@Component public class CustomConfiguration implements WebServerFactoryCustomizer { @Override public void customize(ConfigurableServletWebServerFactory factory) { factory.setPort(9090); } }

Here we are setting server port as 9090 which is hard coded in the code. To avoid hardcoding, we can assign a value from environment using @Value annotation in a bean class and the use it here.

  1. Second precedence is assigned to command line arguments like below:

    java -jar target/spring-boot-0.0.1-SNAPSHOT.jar --server.port=8092

Here we are telling the server to start listening at 8092. Note if we use both the above approaches together, it will ignore command line argument as custom code is given the first precedence.

  1. Third precedence is assigned to OS environment variable. If none of the above two approaches is taken up, Spring will take server port from environment property. In case of deployment on Kubernetes, a property set under env section in Deployment yaml will be used.

  2. Fourth precedence is assigned to profile specific application.properties file.

  3. Fifth precedence is assigned to value assigned in application.properties file (which by default Spring Boot tries to find src/main/resources/config, if not found, then tries to find under src/main/resources).

Most manageable and useful approach can be combination of first and third approach. You can use an environment property and use that custom code.

Sample code:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class EnvironmentCustomizer {
    @Value("${server.port}")
    private int serverPort;
    public void setServerPort(int serverPort) {
        this.serverPort = serverPort;
    }
    public int getServerPort() {
        return serverPort;
    }
}
@Configuration
public class CustomConfiguration
{
    @Autowired
    EnvironmentCustomizer envCustomizer;
    @Bean
    WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerPortCustomizer() {
    return factory -> factory.setPort(envCustomizer.getServerPort());
    }
}
Soumen Ghosh
  • 168
  • 2
  • 11
0

Here's a Kotlin approach for setting the port in code:

fun main(args: Array<String>) {
    runApplication<TestApplication>(*args) {
        setDefaultProperties(mapOf(
            "server.port" to 8081
        ))
    }
}
vilpe89
  • 4,656
  • 1
  • 29
  • 36
-3

In my case adding statement

server.port=${port:8081}

override the default tomcat server port.

Mercurial
  • 25
  • 1
  • 1
  • 5