Connecting to rabbitmq docker container from service in another container

steve picture steve · Nov 12, 2016 · Viewed 21.2k times · Source

I've done a lot of searching but I cannot fix this issue.

I have a basic Rabbitmq container running via this command:

docker run -d --hostname rabbitmqhost --name rabbitmq -p 15672:15672 -p 5672:5672 rabbitmq:3-management

I am using nameko to create a microservice which connects to this container. Here's a basic microservice module main.py:

from nameko.rpc import rpc
class Service_Name(object):
    name = "service_name"

    @rpc
    def service_endpoint(self, arg=None):
        logging.info('service_one endpoint, arg = %s', arg)

This service runs and connects to the rabbitmq from my host machine with the command:

nameko run main --broker amqp://guest:guest@localhost

I wanted to put the service into a Docker container (called service_one) but when I do so and run the previous nameko command I get socket.error: [Errno 111] ECONNREFUSED no matter how I try and link the two containers.

What would be the correct method? The aim is to have each service in a container, all talking to each other through rabbit. Thanks.

Answer

larsks picture larsks · Nov 12, 2016

If you're running a service inside a container, then amqp://guest:guest@localhost won't do you any good; localhost refers to the network namespace of the container...so of course you get an ECONNREFUSED, because there's nothing listening there.

If you want to connect to a service in another container, you need to use the ip address of that container, or a hostname that resolves to the ip address of that container.

If you are running your containers in a user-defined network, then Docker maintains a DNS server that will map container names to addresses. That is, if I first create a network:

docker network create myapp_net

And then start a rabbitmq container in that network:

docker run -d --network myapp_net --hostname rabbitmqhost \
   --name rabbitmq -p 15672:15672 -p 5672:5672 rabbitmq:3-management

Then other containers started in that network will be able to use the hostname rabbitmq to connect to that container.

For containers running in the default network (no --network parameter on the command line), you can use the --link option to achieve a similar, though less flexible, effect, as documented here.