TL;DR: I just want a way to forward trafic to localhost to the host without using --net=host

I'm running multiple containers on the same host, and need them to access an instance of Redis that's available at localhost:6379. Also, I need to use port forwarding, so using --net=host is not an option.

How can I start multiple containers and allow all of them to forward trafic to localhost to the host?

I have also tried docker run --add-host localhost:<private ip address> -p <somehostport>:<somecontainerport> my_image, with no success (I still get that connection to 127.0.0.1:6379 is refused, as if localhost was not resolved to the host's private IP)

2 Answers

0
larsks On

I'm running multiple containers on the same host, and need them to access an instance of Redis that's available at localhost:6379.

You can't.

If something is listening only on localhost, then you can't connect to it from another computer, from a virtual machine, or from a container. However, if your service is listening to any other address on your host, so you can simply point your containers at that address.

One solution is to configure your Redis service to listen on the address of the docker0 bridge, and then point your containers at that address.

0
BMitch On

This is better solved by a small redesign. Move redis into a container. Connect containers via container networking, and publish the redis port to localhost for anything that still isn't in a container. E.g.

docker network create redis
docker run -d --net redis -p 127.0.0.1:6379:6379 --name redis redis
docker run -d --net redis -e REDIS_URL=redis:6379 your_app

Containers need to communicate by the container name over a user created network, so your app will need to be configured with the new redis URL (changing localhost to redis).

The only other solution I've seen for this involves hacking of iptables rules, which isn't very stable when containers get redeployed.