In a Spring Boot application, the default web server port is set to 8080. However, there are various scenarios where you might need to change this port, such as avoiding conflicts with other applications or adhering to specific deployment requirements. This tutorial will guide you through multiple methods to change the default web server port in a Spring Boot application, ensuring you have the flexibility to choose the approach that best fits your needs.
Set the Port in application.properties or application.yml
The simplest way to change the port is by setting the server.port
property in the application.properties
or application.yml
file.
For example, to change the default port to 8081:
server.port=8081
Or, using application.yml
:
server: port: 8081
Use Command Line Arguments to set the Web Port
You can also change the port by passing a command-line argument when starting your Spring Boot application. For example:
java -jar your-app.jar --server.port=8081
Change the Port Porgrammatically
Another programmatic approach is to implement the WebServerFactoryCustomizer
interface.
import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.stereotype.Component; @Component public class ServerPortCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> { @Override public void customize(ConfigurableWebServerFactory factory) { factory.setPort(8081); } }
Alternatively, you can use as Type the Factory to your Web Server. This is useful if you wantto apply some properties which are specific to your Web Server:
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.stereotype.Component; @Component public class TomcatCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> { @Override public void customize(TomcatServletWebServerFactory factory) { factory.setPort(8080); } }
Using different profiles
Finally, if your application uses multiple profiles, you can define the Web Server port in each profile of your choice. For example:
application-dev.properties
:
server.port=8081
application-prod.properties
:
server.port=8082
Activate the profile when starting the application:
java -jar your-app.jar --spring.profiles.active=dev
Conclusion
This article provided guidance on how to change the default HTTP Port of Tomcat Web Server either through configuration or programmatically.
Found the article helpful? if so please follow us on Socials