How to manage large number of ports?
I'm running a lot of services (most of them are docker-managed). I struggle with managing port numbers for all of them. The problem arises when I want to spin a new e.g. HTTP server. I have to look for a port number that hasn't been already taken by other services. Currently, when I want to spin a new server, I look for all taken ports in docker ps
if for example taken ports are 8001, 8002, 8003,...8051, then I assign port 8052. It works fine until some service becomes temporarily dead, thus doesn't show up in docker ps
, I assign its port to new service, and when the old one is restored I have ports collision.
I'm already using Nginx for reverse proxy to expose my servers to public network. But this doesn't solve my problem. I still have to somehow find the latest unused port number, and neither nginx.conf
nor docker ps
is single-source-of-truth in this situation.
Is there any solution for managing ports? Some registry?
Solution 1:
Let Docker find a free port for you when you create the container.
From the documentation:
you may specify a range of host ports to bind a container port to that is different than the default ephemeral port range:
$ 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.
You can get the exposed port afterwards with docker inspect
, for example like this:
docker inspect --format '{{ range .HostConfig.PortBindings }}{{ range . }}{{ . }}{{ end }}{{ end }}' container
{127.0.0.1 8095}
Configuration of my test container:
"PortBindings": {
"8080/tcp": [
{
"HostIp": "127.0.0.1",
"HostPort": "8095"
}
]
}