Wednesday, June 4, 2025

SpringBoot: Assign a port number dynamically

 Most of the time we give the port number in the application properties files under "server.port"

Or lese when we start the application eg: run as jar file with java -jar using -D option we can asign a port number

java -jar -Dserver.port=8888

Or in running application in IDE , you can configure the port number which is more or less the same.


Solution:

Simply assign the "server.port" to zero

server.port=0

This will dynamically assign a port at run time.


So how find the dynamic port number

1. you can find from application start console logs

2. Form Eureka server

    Simply click the lik , it will go to actuator point with the port number

eg:http://user-home:64192/actuator/info



For your info, i will put a sample log also.

--------------------------------------------------------------------------------------------------------

2025-06-04T15:03:50.374+05:30  WARN 19248 --- [rest-client-with-feign] [           main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.

2025-06-04T15:03:50.461+05:30  INFO 19248 --- [rest-client-with-feign] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 64192 (http) with context path '/'

2025-06-04T15:03:50.476+05:30  INFO 19248 --- [rest-client-with-feign] [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 64192

2025-06-04T15:03:50.488+05:30  INFO 19248 --- [rest-client-with-feign] [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING

2025-06-04T15:03:50.530+05:30  INFO 19248 --- [rest-client-with-feign] [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1

-----------------------------------------------------------------------------------------------------




No comments:

Post a Comment