Is there a way to reset the port Docker allocates from a port range?

Viewed 389

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?

1 Answers

In docker documentation for ephemeral port range they stated:

$ docker run -d -p 8000-9000:5000 training/webapp python app.py

This would bind port 5000 in the container to a randomly available port between 8000 and 9000 on the host.

Even they say it is random, based on the scenario you show in the question and my experience with docker networks I'm almost sure there is a counter mechanism. I have created a CI pipeline that uses docker as infrastructure. I used HAProxy and it gone very smooth. I highly recommend HAProxy.

Related