Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Changing the Default Port of Spring Boot Apps [Snippets]

DZone's Guide to

Changing the Default Port of Spring Boot Apps [Snippets]

Let's take a look at three different approaches you can take to defining your Spring Boot app's default Tomcat port, as well as the impacts of those approaches.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

By default, Spring Boot applications run on an embedded Tomcat via port 8080. In order to change the default port, you just need to modify the server.port attribute, which is automatically read at runtime by Spring Boot applications.

In this tutorial, we provide a few common ways of modifying the server.port attribute.

application.properties

Create an application.properties file under src/main/resources and define the server.port attribute inside it:

server.port=9090


EmbeddedServletContainerCustomizer

You can customize the properties of the default servlet container by implementing the EmbeddedServletContainerCustomizer interface as follows:

package com.programmer.gate;
 
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
 
public class CustomContainer implements EmbeddedServletContainerCustomizer {
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(9090);
    }
}


The port defined inside the CustomContainer always overrides the value defined inside application.properties.

Command Line

The third way is to set the port explicitly when starting up the application through the command line. You can do this in two different ways:

  • java -Dserver.port=9090 -jar executable.jar
  • java -jar executable.jar –server.port=9090

The port defined using this way overrides any other ports defined through other ways.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,spring boot ,default port ,configuration

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}