Open Ports on Docker Containers Without a Restart or Setup Adjustment
Suppose you have a container running, and it doesn't have the port you want, like a debugger port or a database port, exposed. Normally, you don't need it, so it's not set up to be exposed. Sure, you could change that configuration, but it's not necessary and takes time.
There is a better way to do that. It's easy but not quite obvious. There is a Unix tool called socat that lets you redirect traffic from your local port to any other port running elsewhere. It's really simple to use.
docker run --net=network -p 5000:5000 alpine/socat TCP-LISTEN:5000,fork TCP:target:5000
The snippet above lets you expose a port running in the target container on port 5000 (for UDP just change TCP to UDP), given it is in the same Docker network as the container you want to expose the port for. You can simply check the name of the network with a simple Docker inspect and jq.
docker ps -a | fzf | awk -F ' ' '{print $1}' | xargs docker inspect | jq ".[0].NetworkSettings.Networks | keys | .[0]"
So there it is. A quick tip on how to expose any port on any container you have. Of course, whether you can connect to the service running on this port is another matter, as, for example, a web server can be configured not to accept traffic from any source. Usually, for a local setup, it shouldn’t be a problem though.
Socat is far more powerful than just this simple use case, and it’s worth learning. But for a quick and dirty solution, the snippet above is good enough.
Subscribe to my newsletter
Read articles from Mariusz “Sielakos” Sielski directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by