simen-andresen
simen-andresen

Reputation: 2327

Accessing rabbitmq running on local machine from docker container

I want to test a docker image running a python script subscribing to a rabbitmq queue. I have rabbitmq running on my local machine, and want to test the docker container running on the same machine and have it subscribe to the local rabbimq server.

I want the script to read environment variables 'QUEUE_IP' set in the docker run command.

The python script:

#!/usr/bin/env python
import pika

host = os.environ.get('QUEUE_IP')

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host=host))

channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
   print(" [x] Received %r" % body)

channel.basic_consume(callback,
                  queue='hello',
                  no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

It doesnt work if QUEUE_IP = 127.0.0.1, and I also tried using the local ip address of the machine, but I only get

pika.exceptions.ProbableAuthenticationError

Is there any easy way of accessing the local rabbitmq from the docker container ?

Upvotes: 2

Views: 2406

Answers (3)

Siyaram Malav
Siyaram Malav

Reputation: 4688

After trying lot of solutions, i came up with working solution.

You need to use the rabbitMQ host(mainly) in docker container where we are trying to make connection to rabbitMQ(which is locally setup)

host - host.docker.internal
port - 5672
user - guest (default)
password - guest (default)

This will save time for lot of people, i am sure.

Thanks.

Upvotes: 1

simen-andresen
simen-andresen

Reputation: 2327

A solution that works is to simply add the --net=host parameter to docker run, e.g.:

docker run -d --net=host my/container

This way, the host's network is shared with the container and it can access the rabbimq server with the localhost ip (127.0.0.1)

Upvotes: 2

MatFiz
MatFiz

Reputation: 1003

According to Docker CLI docs:

Sometimes you need to connect to the Docker host from within your container. To enable this, pass the Docker host’s IP address to the container using the --add-host flag. To find the host’s address, use the ip addr show command.

So all you need to do is set: QUEUE_URL to the output of ip addr show.

Upvotes: 2

Related Questions