Setting a Random Port in Spring Boot Application at startup

Carvia Tech | December 03, 2019 | 2 min read | 1,743 views


Why do we need random port

If we want to run multiple instances of single app on same server, then we need to assign a different port at runtime. To solve this problem we need to choose random available port at app startup. Since the app will register itself with eureka service registry, other apps can still discover this service through service registry.

Using properties to set the random port

We can set fixed and random port using application.yml in any spring boot aplication.

To set a fixed port, we use the following configuration:

application.yml - fixed port
server.port: 9090

Spring boot will assign a random port if we set it to 0 in application properties.

application.yml - random port
server.port: 0

We can set a random port in a custom predefined range using the below configuration.

application.yml - random port in custom range [5000-5100]
server.port: ${random.int(5000,5100)}

Using SocketUtils to set random the port

Spring boot provides a convenient class SocketUtils to determine if a port is available or not.

SocketUtils

SocketUtils is Simple utility methods for working with network sockets — for example, for finding available ports on {@code localhost}.

Within this class, a TCP port refers to a port for a {@link ServerSocket}; whereas, a UDP port refers to a port for a {@link DatagramSocket}.

Utility class that search available port in custom range
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.SocketUtils;
import org.springframework.util.StringUtils;

public class SpringBootUtil {
    final static Logger log = LoggerFactory.getLogger(SpringBootUtil.class);

    public static void setRandomPort(int minPort, int maxPort) {
        try {
            String userDefinedPort = System.getProperty("server.port", System.getenv("SERVER_PORT"));
            if(StringUtils.isEmpty(userDefinedPort)) {
                int port = SocketUtils.findAvailableTcpPort(minPort, maxPort);  (1)
                System.setProperty("server.port", String.valueOf(port));
                log.info("Random Server Port is set to {}.", port);
            }
        } catch( IllegalStateException e) {
            log.warn("No port available in range 5000-5100. Default embedded server configuration will be used.");
        }
    }
}
1 SocketUtils.findAvailableTcpPort method finds an available TCP port randomly selected from the range
Spring Boot Main Application
@SpringBootApplication
public class Application {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringBootUtil.setRandomPort(5000, 5500);   (1)
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        logger.info("Application " + ctx.getApplicationName() + " started");
    }
...
}
1 Calling the custom method to set the random available port within range [5000-5500] and update the server.port property as well.

Now we have enabled our spring microservice to start on a random available port in predefined range. This port will be registered in Eureka Service Discovery so that other peer services can access this microservice.


Top articles in this category:
  1. Run method on Spring Boot startup
  2. Custom banner in spring boot
  3. Sendgrid Dynamic Templates with Spring Boot
  4. Redis rate limiter in Spring Boot
  5. Feign RequestInterceptor in Spring Boot
  6. Spring RestTemplate Basic Authentication
  7. SendGrid emails in Spring Boot


Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info