1 min read

Docker Listen Port for Only Localhost

When enabling port listening on Docker, it is set to listen on all interfaces by default, including your local network and any public interfaces.

docker run -p 3100:3100 some-image

To verify this, you can use Telnet with the public IP:

telnet public-ip 3100
 
Connected to localhost.
Escape character is '^]'.

If you want to limit the listening to the local network or localhost only, you cannot do this:

docker run -p localhost:3100:3100 some-image

This will result in an error:

1 error(s) decoding:
 
* error decoding 'Ports': Invalid ip address: localhost

Instead, use a direct IP address:

docker run -p 127.0.0.1:3100:3100 some-image

To verify, test it with Telnet again. You should see something like this when accessing it via the public IP.

telnet public-ip 3100
 
telnet: Unable to connect to remote host: Connection refused

Or using netstat:

netstat -tulpn | grep 3100
tcp        0      0 127.0.0.1:3100          0.0.0.0:*               LISTEN      2503684/docker-prox

If your container is already running using Docker Compose, you can’t just restart it; you need to take it down and bring it back up again.

In my case, I am now able to proxy my Docker container using Nginx proxy pass and set the upstream to localhost:3100.