Context:
When mapping a container port into a port range, Docker seems to always increment the allocated port each time the container runs, even if the "lower" ports are already available.
To explain my point, as a minimal reproducible example, I'll use nginxdemos image. Consider a docker-compose.yml with the following contents:
version: '3'
services:
hello:
image: nginxdemos/hello
ports:
- "8080-8085:80"
The port range is useful when using the scale flag, so it should be kept. Now, when I execute docker-compose down and docker-compose up, I would expect that the port resets to the first one available in the range (8080), but that is not what happens.
$ docker-compose up -d
$ docker port nginxdemos_hello_1
80/tcp -> 0.0.0.0:8080
$ docker-compose down
$ docker-compose up -d
$ docker port nginxdemos_hello_1
80/tcp -> 0.0.0.0:8081
Instead, Docker keeps a counter somewhere and just increments it. As far as I've seen, the counter resets only in the following scenarios:
- The counter overflows the range limit
- The Docker daemon is restarted
- The port mapping is changed
This behaviour is not specific to docker-compose, because the same happens for docker run. It also seems consistent across different host operating systems.
$ docker run --rm --name hello -d -p "8080-8085:80" nginxdemos/hello
$ docker port hello
80/tcp -> 0.0.0.0:8082
$ docker kill hello
$ docker run --rm --name hello -d -p "8080-8085:80" nginxdemos/hello
$ docker port hello
80/tcp -> 0.0.0.0:8083
Question:
For quick testing, this can be a little annoying because it's always necessary to check which ports are in use.
I know I can just use an HA Proxy to abstract me from this. But I'm just wondering: Assuming this is the normal behaviour, is there a way to reset this counter using some sort of flag, i.e, without changing the port mapping and without restarting the Docker daemon? Or is the HA Proxy my best shot?