I want to start Spring Cloud application (Spring Boot 1.5.14, Spring Cloud Edgware.SR4) on a random port in a given range (5001-5100). I know we can specify random port in Spring Boot application using server.port=0
, but I am facing these two issues:
server.port=0
, does spring cloud support dynamic ports?Using properties to set the random port We can set fixed and random port using application. yml in any spring boot aplication. Spring boot will assign a random port if we set it to 0 in application properties. We can set a random port in a custom predefined range using the below configuration.
These are randomly selected and used for temporary connections. 1024-5000 have been used by a number of OSes. IANA officially recommends 49152-65535 for the Ephemeral Ports. Port 8080 is the most common "high" port that people use (i.e. alternate web server port).
To get the server address you can use the InetAddress class to get the local ip-address, for the port you can use ${server. port:8080} is you are using tomcat (this trick would also work for the server.
Instead of using SocketUtils to find an available local port for a server, it is recommended that you rely on a server's ability to start on a random port that it selects or is assigned by the operating system. To interact with that server, you should query the server for the port it is currently using.
Spring provides utility class to scan available TCP port, so I have used the below method to set a random server port.
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);
System.setProperty("server.port", String.valueOf(port));
log.info("Server port set to {}.", port);
}
} catch (IllegalStateException var4) {
log.warn("No port available in range 5000-5100. Default embedded server configuration will be used.");
}
}
Now this method can be called in main class of Spring Boot Application before starting the spring context, just like this:
public static void main(String[] args) {
setRandomPort();
ApplicationContext ctx = SpringApplication.run(Application.class, args);
logger.info("Application " + ctx.getApplicationName() + " started");
}
Now this random port configuration works fine in Spring Cloud environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With