vidriduch
vidriduch

Reputation: 4863

how does docker auto allocate and recycle ports for containers

When I run docker command

docker run -d -P nginx

docker will run and auto allocate port for nginx's port 80. If I stop the image and start it again, a new port will be allocated to nginx (normally next one available).

As I found out, the range for port allocation is based on ephemeral port range , in docker case default is 32768 - 61000. (https://docs.docker.com/v17.09/engine/userguide/networking/default_network/binding/)

How and when does docker recycle ports? Will it go back to 32768 or nearest available?

Upvotes: 3

Views: 1297

Answers (1)

scipsycho
scipsycho

Reputation: 587

It took a lot of time for me to find out but docker doesn't do much.

I dived into docker-ce source files and saw that it uses a function RequestPortInRange which simply gives the next available port.

Now, when you run docker run -d -P nginx command, docker gives you the first available port in the "ephemeral range" i.e. 32768 - 61000 ( as you pointed out).

Once you destroy /stop the container, it should resume to 32768, However, it goes to the next available port i.e. 32769 ( on my computer at least).

So, I thought may be it takes sometime for linux or any OS to take back the port after the container is destroyed but netstat -lntu confirms that the port isn't in use any more.

So, my theory is (which may be entirely wrong, in which case I will be glad to be corrected ), that it creates one instance of PortAllocator thing and thus it has a state. so, the next time docker run -P ... is called, it goes for the next available port. This is also corroborated by the fact that even when you create other containers, the docker engine is providing you the next available port not the previous yet available ones.

I hope i answered your question and i don't know much of golang so, forgive any mistake in terminology.

Upvotes: 6

Related Questions