Docker – How to access host port from docker container

dockernetworkingport

I am trying to access a service at a specific port on the host from inside a docker container. But all I am getting is Connection refused.
For debugging purposes, I create a dummy listening port via nc:

host$ nc -l 888
...

And in the container I do

container$ ping 172.16.238.1
PING 172.16.238.1 (172.16.238.1) 56(84) bytes of data.
64 bytes from 172.16.238.1: icmp_seq=1 ttl=64 time=0.071 ms

container$ nc -zv 172.16.238.1 888
172.16.238.1: inverse host lookup failed: Unknown host 
(UNKNOWN) [172.16.238.1] 888 (?) : Connection refused

I am not irritated by the failing inverse host lookup, as explained at https://stackoverflow.com/questions/48779583/nc-command-inverse-host-lookup-failed-unknown-host .

Some similar questions pointed out that the binding address must match, but that seems to be fine:

host$ lsof -i -P -n | grep LISTEN
nc        13405 richardkiefer    3u  IPv4 0x69a18bda503dc55d      0t0  TCP *:888 (LISTEN)

I know that you can assign containers the host's network, which seems to fix this in other similar questions, but for security reasons I like to avoid that.

My motivation are testing and development purposes, where I would like to reach an ssh tunneld port on my host machine (ultimately reaching a remote host), so I am aware that I can link containers running different services as adviced in connecting from docker container to docker host and it does not solve my use case.

The host is macos and the firewall according to system settings is turned off.

Any suggestions? Many thanks in advance!

Best Answer

Do not know if you have tried to contact the host from within the container via host address host.docker.internal which is a special DNS name on Mac and Windows for dev/test only. I have not tried it myself but was looking for similar for Linux.

https://docs.docker.com/docker-for-mac/networking/

Cheers!

Related Topic