How to configure port for a Spring Boot application

926,496

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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);
        });
    }
}

Solution 5

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 (clues were here):

mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085
Share:
926,496
Paul Verest
Author by

Paul Verest

Java Developer, Architect, Team Leader; Agile Coach, Tech Manager Authoring Nodeclipse, Anide.js, Enide Organizing http://szjug.github.io/ Building up JVMs, Spring.io and Node.js User Groups (Java, Groovy, Scala, Android, JavaScript)

Updated on July 08, 2022

Comments

  • Paul Verest
    Paul Verest almost 2 years

    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.

    • Betlista
      Betlista about 6 years
      If someone interested, here is shown how to have multiple ports - stackoverflow.com/questions/36357135/…
    • Keaz
      Keaz almost 6 years
      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
    • Lahiru Samishka
      Lahiru Samishka over 4 years
      your project [application.properties] for add the server.port=8080
    • Atif
      Atif about 4 years
      set server.port=8080 in application properties. this configuration is in ServerProperties.class class under org.springframework.boot.autoconfigure.web.
  • Erik Martino
    Erik Martino over 9 years
  • yathirigan
    yathirigan about 9 years
    this didn't seem to work. I used server.port in the application.yml and it worked
  • azizunsal
    azizunsal almost 9 years
    When random port is used, port info can get with @Value("${local.server.port}")
  • alpert
    alpert over 8 years
    Actually command line option is --server.port=8090 not -Dserver.port=8090. docs.spring.io/spring-boot/docs/current/reference/html/…
  • sargas
    sargas over 8 years
    As a compliment to this answer: According to the spring docs there are other paths you can put application.properties on. In my case that helped a lot.
  • Soumya Kanti
    Soumya Kanti over 8 years
    -Dserver.port=XXXX did not work for me. I used OS environment variable mode: $ SERVER_PORT=8090 java -jar <path/to/my/jar>
  • Xdg
    Xdg over 8 years
    This is working and very useful, when you have port in your own config file and want to set it during runtime.
  • Martin Hansen
    Martin Hansen over 8 years
    This was helpful when i needed to deploy an application to a AWS Elastic Beanstalk service, to get the port from an environment variable.
  • Mike3355
    Mike3355 about 8 years
    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.
  • Priidu Neemre
    Priidu Neemre almost 8 years
    This is super useful when all you want is a self-contained unit or integration test, +1.
  • JimHawkins
    JimHawkins almost 8 years
    Welcome to SO :-) please look at How to Answer
  • higuaro
    higuaro over 7 years
    Very useful when the env variable for port is already defined under a different name.
  • Lucky
    Lucky over 7 years
    Is'nt it the @Configuration instead of @Controller? Please update if so.
  • Lucky
    Lucky over 7 years
    Or Also if you are using Intellij IDEA the autocomplete works too. ;)
  • Lucky
    Lucky over 7 years
    Do you mean application.yml and what IDE are you using? Please be specific.
  • rzymek
    rzymek over 7 years
    java -jar <my.jar> --server.port=8090 works in spring 1.4.0
  • tan9
    tan9 over 7 years
    Both (1) java -Dserver.port=XXXX -jar <path/to/my/jar> and (2) java -jar <path/to/my/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 <path/to/my/jar> --server.port=YYYY, YYYY takes precedence over XXXX, this is why Spring Boot Externalized Configuration is so charming.
  • hd1
    hd1 about 7 years
    System.setProperty("server.port", 80); is another way to achieve the same.
  • kap
    kap about 7 years
    It should be @Configuration, but if you import it using @Import it works, not sure if it is working with auto configuration search.
  • David Pham
    David Pham over 6 years
    Many ways to change port on Spring Boot tomcat javabycode.com/spring-framework-tutorial/spring-boot-tutoria‌​l/…
  • Yogesh Borkhade
    Yogesh Borkhade over 6 years
    src/resources/application.properties server.port=8080 or
  • jorgen.ringen
    jorgen.ringen about 6 years
    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: docs.spring.io/spring-boot/docs/current/reference/html/…
  • Betlista
    Betlista about 6 years
    Why to add same asnwer one year later?!? and server.port 8080 is wrong syntax for Java property file...
  • PeMa
    PeMa about 6 years
    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?
  • mapm
    mapm about 6 years
    Starting from Spring Boot 2, you should use spring-boot.run.jvmArguments.
  • old-monk
    old-monk about 6 years
    In case you prefer maven, do this mvn spring-boot:run -Dserver.port=8888
  • geek
    geek almost 6 years
    application.yml => server: port: 8090
  • jocull
    jocull almost 6 years
    Here's a current link to the programmatic override section: docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/…
  • Brent Bradburn
    Brent Bradburn over 5 years
    SERVER_PORT=8081 mvn spring-boot:run
  • chethu
    chethu about 5 years
    application.yaml can also be used instead of properties.
  • Milgo
    Milgo about 5 years
    Using the HashMap will work only if no port is set in applications.properties or .yml.
  • serv-inc
    serv-inc almost 5 years
    In STS 4 it is at run -> run configurations -> main, then scroll down to Table with Parameter Name and Value
  • nikiforovpizza
    nikiforovpizza almost 5 years
    it's a dublicate answer
  • Sudip Bhandari
    Sudip Bhandari almost 5 years
    I can't think of a scenario where you would want to have random port number
  • iQuestProgrammer
    iQuestProgrammer over 4 years
    for application.properties its server.port = 8291
  • Luis Mauricio
    Luis Mauricio over 4 years
    @hd1, I added our answers to the main answer, check it out and modify as you se fit please
  • velocity
    velocity over 3 years
    -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
  • Heybat
    Heybat over 3 years
    interesting, I didn't know that it is possible to do it programmatically. Thanks for info
  • Dirk Schumacher
    Dirk Schumacher almost 3 years
    Why are there dots behind the given port '8080.' and '0.' ?
  • SeverityOne
    SeverityOne almost 3 years
    What do Maven and Gradle have to do with whether you use a properties or YAML file? The build process (Maven) is completely disparate from the application framework (Spring Boot).
  • Javi Vazquez
    Javi Vazquez almost 3 years
    I agree A) and B) should be your options if you are not doing anything weird
  • user2081279
    user2081279 over 2 years
    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!
  • Philip Rego
    Philip Rego over 2 years
    This does not work
  • Philip Rego
    Philip Rego over 2 years
    This doesn't work. What application.properties? Which properties can overwrite this one? How can I be sure Spring is picking it up?
  • Anuj Dhiman
    Anuj Dhiman over 2 years
    There is nice explanation of ways to change port of spring boot javavogue.com/2019/02/…