In Spring Boot, you can run your application on a custom port by specifying the desired port number in your application configuration. There are several ways to achieve this:
-
Using application.properties or application.yml:
You can define the port number in the
application.properties
file orapplication.yml
file under thesrc/main/resources
directory. Simply add a property likeserver.port
and set it to the desired port number. For example:# application.properties server.port=8081
# application.yml server: port: 8081
-
Using Command-line Arguments:
You can specify the port number as a command-line argument when running your Spring Boot application. Use the
--server.port
option followed by the desired port number. For example:java -jar your-application.jar --server.port=8081
-
Using Environment Variables:
You can set an environment variable to define the port number. Spring Boot automatically maps certain environment variables to configuration properties. For example, you can set the
SERVER_PORT
environment variable to the desired port number:export SERVER_PORT=8081
-
Programmatically in Code:
You can programmatically set the port number in your Spring Boot application code. This approach is less common but can be useful in certain scenarios. For example:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() { return factory -> factory.setPort(8081); } }
Choose the method that best suits your requirements and preferences. Each approach provides flexibility in configuring the port for your Spring Boot application.