Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

python - Connecting to rabbitmq docker container from service in another container

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...