2

I've seen several variants of this apparently common scenario but all the offered solutions are specific to each case (for example, if the service you want to share is say, MySQL, share the sock file).

I have a service on the host. For simplicity's sake let's say it's netcat listening on 127.0.0.1:5000 TCP.

I need to connect from a container to that address using another netcat, or telnet, and be able to send and receive data.

The host service needs to be in 127.0.0.1 (and not another IP) for a few reasons (including security) and the service is unable to bind to more than one interface. Using 0.0.0.0 is really not an option.

In theory this seems like something that IP tables should be able to solve, but I haven't been able to get it to work, so I assume it's Docker filtering out packets before the rules in the host have a chance to process them (iptables logging doesn't show any packet being received in the host).

Edit: If possible I'd like to avoid the host network driver.

2 Answers2

4

Figured it out. As usual, things are really easy one you know them.

Anyway these are the 3 things I had to do:

1) In the firewall, accept connections from the bridge interfaces

iptables -A INPUT -i br+ -p TCP --dport 5000 -j ACCEPT

2) In prerouting change the destination IP:

iptables -t nat -I PREROUTING  -d 172.17.0.1 -p tcp --dport 5000 -j DNAT --to 127.0.0.1:5000

3) Allow non-local IPs to connect to the loopback:

sysctl -w net.ipv4.conf.all.route_localnet=1

The last one probably a bit unsafe as is, should be changed to just the bridges (instead of "all").

After doing this, the containers can connect to 172.17.0.1:5000 and the service which is running on the host listening only to 127.0.0.1:5000 handles the connection correctly.

0

From inside of a Docker container, how do I connect to the localhost of the machine?

According to this, you should be able to point 127.0.0.1 to host.docker.internal.

Why would you like to avoid the host network driver? And why don't you put the host's service into a container as well? That would solve a lot of your problems.