1. Overview

This article contains how to change Spring boot change port using application.properties or application.yml as well as using EmbeddedServletContainerCustomizer. server.port will work for Tomcat, Jetty as well as Undertow application Server.

If the port is already used by another application then it will generate exception like:

The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the
connector may be misconfigured.

After update port requires to restart spring boot application.

2. Spring boot change port ways

2.1 Spring Boot change port using application.properties

In a standalone application, the main HTTP port defaults to 8080, but can be set with server.port (e.g. in application.properties or as a System property).

application.properties

server.port=8585

application.yml

server:
  port: 8585

2.2 Spring Boot change port using  EmbeddedServletContainerCustomizer

package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@SpringBootApplication
@ComponentScan
// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            container.setPort(8012);           // your new port
        });
    }
}

2.3 Change port using Command line:

Pass JVM argument -Dserver.port and pass new port, application start using that port. It will override application.properties|.yml port value.

java -jar -Dserver.port=8989 spring-boot.jar

Output:

2017-07-20 23:07:38.765 INFO 56804 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8012 (http)
2017-07-20 23:07:38.770 INFO 56804 --- [ main] com.javadeveloperzone.SpringBootConfig : Started SpringBootConfig in 4.03 seconds (JVM running for 4.574)

3. References

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *