Out of the box, Spring boot applications use the embedded tomcat server start at default port 8080
. You can change the default embedded server port to any other port, using any one of following options.
1. Change the default port in application.properties file
This file is provided as empty file when you create a simple Spring Boot application with the inizializr application:
Changing the server port is just a matter of setting:
server.port=8081
|
On the other hand, if you are using YAML files for your external configuration, the following will do:
server: port : 8081
|
2. Change the server port programatically
EmbeddedServletContainerCustomizer interface is used to customize embedded tomcat configuration. Any beans of this type will get a callback with the container factory before the container itself is started, so we can set the port
, address
, error pages
etc.
2.1. Spring boot2 – WebServerFactoryCustomizer interface
Change default server port in spring boot2 applications by implementing ConfigurableWebServerFactory
interface.
@Component public class AppContainerCustomizer implements WebServerFactoryCustomizer< ConfigurableWebServerFactory > { @Override public void customize(ConfigurableWebServerFactory factory) { factory.setPort(8081 ); } } |
3. Use the command line
Last but not least, yu can use the command line to set the Web server port by specifying ‘server.port’ as argument during application run command.
$ java -jar -Dserver.port=8081 spring-boot-example.jar |