server.port: 9090
Setting a Random Port in Spring Boot Application at startup
Upasana | 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:
Spring boot will assign a random port if we set it to 0
in application properties.
server.port: 0
We can set a random port in a custom predefined range using the below configuration.
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
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}. |
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 |
@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:
- Run method on Spring Boot startup
- Running Spring Boot app as a service in unix
- Custom banner in spring boot
- Feign Client Logging and connection timeout
- Redis rate limiter in Spring Boot
- SendGrid emails in Spring Boot
- Feign RequestInterceptor in Spring Boot