0

I've been trying to containerize two hello-world python apps (a consumer and a producer) and let them talk to each other via RabbitMQ. Locally, when using localhost as the host name for the pika connection, everything works fine. I can send and consume messages on the 5672 port and on the 15672 I am able to visualize the queue working as intended.

The problem arises when I try to put those two apps in containers.

The consumer:

import pika, sys, os, socket

local_ip = socket.gethostbyname(socket.gethostname())
print(local_ip)


def main():
    connection = pika.BlockingConnection(pika.ConnectionParameters(host=str(local_ip)))
    channel = connection.channel()

    channel.queue_declare(queue='hello')

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

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

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

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

As you can see, I edited the host parameter to fetch the host ip since with localhost I got this error:

Traceback (most recent call last):
  File "/app/consumer.py", line 23, in <module>
    main()
  File "/app/consumer.py", line 8, in main
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
  File "/usr/local/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 360, in __init__
    self._impl = self._create_connection(parameters, _impl_class)
  File "/usr/local/lib/python3.10/site-packages/pika/adapters/blocking_connection.py", line 451, in _create_connection
    raise self._reap_last_connection_workflow_error(error)
pika.exceptions.AMQPConnectionError

Apparently though, that's not the issue since I'm getting the same exact error passing the host ip.

I am running the RabbitMQ server in docker using the community image rabbitmq:3-management.

This is the Dockerfile for this consumer file:

FROM python:rc-alpine

RUN mkdir /app
WORKDIR /app
ADD . /app/
RUN pip install -r requirements.txt

EXPOSE 5672

CMD ["python", "/app/consumer.py"]

What should I do to solve this issue? I'm pretty sure it's a trivial one, but I'm struggling a lot with it.

  • Is RabbitMQ also running in a container (maybe using Docker Compose) or outside a container on the host? – David Maze May 10 '21 at 10:26
  • It is running in a container. I used the standard command: docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management – obr3ptox May 10 '21 at 10:27
  • All of the containers need to be on the same `--net`; the question I link to above gives an example. Then you can use `rabbitmq`, the container's `--name`, as a host name when calling between containers. – David Maze May 10 '21 at 10:33

0 Answers0