How to Run Multiple Spring Cloud Instances Locally Using Random Ports

Learn how to launch several Spring Cloud microservice instances on a single machine without manually editing configuration files by leveraging random ports and adjusting Eureka instance IDs for proper registration.

Programmer DD
Programmer DD
Programmer DD
How to Run Multiple Spring Cloud Instances Locally Using Random Ports

When developing Spring Cloud microservices, testing high‑availability components such as the service registry and configuration server often requires running multiple instances of the same application on a local machine. Because a single Java process can bind to only one port, developers traditionally modify server.port in the configuration file for each instance, which is cumbersome.

This article presents a simpler approach: let Spring assign a random port to each instance, eliminating the need to edit configuration files before each start‑up.

Method 1 – Set server.port=0

Adding the following line to application.properties tells Spring Boot to pick an available random port at launch: server.port=0 However, when the service registers with Eureka, all instances appear with the same instance name (e.g., Lenovo-zhaiyc:hello-service:0), causing Eureka to treat them as a single instance. To differentiate them, override the instance ID using a random value:

eureka.instance.instance-id=${spring.application.name}:${random.int}

Method 2 – Use a random range for server.port

Instead of setting the port to zero, you can directly assign a random port within a specific range using Spring’s random.int function: server.port=${random.int[10000,19999]} Because the default instance ID includes the port number, each instance automatically receives a unique ID without additional configuration.

Both techniques allow developers to start multiple Spring Cloud services locally with minimal effort, facilitating testing of load balancing, service discovery, and configuration management.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

MicroservicesSpring BootSpring CloudRandom Port
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.