0

I am trying to create and start a container from within my REST service method. My REST service is residing in an Unix machine and there would be multiple requests from external systems to configure and start multiple docker containers in the machine using my REST service that also resides in the same machine.

My question is how do I decide on which port I can start my container. Each request to my REST method should start a container on a unique port that has not been used in earlier requests. If I generate a random port number then I need some way to ensure that the same number is not regenerated, otherwise it would create a port conflict.

I need to generate a random port number each time, non repeating, store the used port list somewhere and check the list each time I generate a random number to make sure the port has not been used, release the port when the container is stopped (update the "ports-in-use" list to remove the stopped container). any idea on how to accomplish this in Java? Thanks in advance

user1722908
  • 535
  • 2
  • 9
  • 21

1 Answers1

1

Why would you randomise the port assignation ?

Just take a range of port you want to use on your machine (let's say 28000 to 28900)

When your REST service is called, you'll just have to check which is the first available port of this range and use it.

Why would you make it hard when it can be easy ? ^^

If you really need to randomise ignoring already taken port, then you can check this thread: Generate random numbers except certain values

Community
  • 1
  • 1
Grégory Elhaimer
  • 2,731
  • 1
  • 16
  • 21
  • Any pointers on how do we check the first available port in a range ? – user1722908 Feb 02 '17 at 18:41
  • Since you store the list of busy port. You can loop trough this list to find the first hole in the chain (first empty) or the next available port if loop reached the end of ports list – Grégory Elhaimer Feb 07 '17 at 14:59