Docker Compose: Port mapping by selecting a random port within given port range

Viewed 902

One thing I am trying to accomplish is that I have a single port exposed from the container(8001).I want to map this container port with a host port. But I want make this host port as randomly selected port from a given port range(8081-8089). Below is the syntax

ports:
  - "8081-8089:8001"

If I use docker-compose v1.29.2 , its working as expected(Selecting single random port within given range). But when I try to use docker-compose v2 its not mapping a single port instead its running container on all ports of given range(8081-8089).

I haven't been able to find a way to do this in the Docker documentation. Do we have any flag which enables this functionality in docker-compose v2? or is it not supported in docker compose v2?

1 Answers

There's no way to do this in Linux in general. You can ask the OS to use a specific port or you can ask the OS to pick a port for you, but you can't constrain the automatically-chosen port.

In a Compose context you can omit the host port to let the OS choose the port

ports:
  - "8001" # container port only

and you will need to use docker-compose port to find out what the port number actually is. That will be any free port number, and there is no way to limit it to a specific range.

Related