Search code examples
pythondockerrabbitmqpika

RabbitMQ returning 404 closed by broker


I have a RabbitMQ docker image i ran using the following commands:

docker pull rabbitmq

sudo  docker run -d -p 5672:5672 -p 15672:15672  --name rabbitmq rabbitmq     

Afterwards i try to run a python client with the pika module to get a connection to the rabbitmq server.

Before starting the server it gave a ConnectionRefusedError but after i have ran the image i get the following error:

pika.exceptions.ChannelClosedByBroker: (404, "NOT_FOUND - no queue 'logs' in vhost '/'")

Here is my python script that i use to establish a connection:

from connection_manager import ConnectionManager
from mq_handler import MessageBroker

rabbit_mq_conn = ConnectionManager.init_connection()
mb = MessageBroker(rabbit_mq_conn)

if __name__ == "__main__":
    mb.run()

Solution

  • Here's a piece of code that works with pika and the Rabbit MQ docker container. It solves at least one issue that you seem to have, which is not creating a queue before using it.

    import pika 
    
    url = <rabbitMQ URL>
    params = pika.URLParameters(url)
    params.socket_timeout = 5
    
    connection = pika.BlockingConnection(params) # Connect to CloudAMQP
    channel = connection.channel() # start a channel
    channel.queue_declare(queue='my_channel') # Declare a queue
    # send a message
    
    channel.basic_publish(exchange='', routing_key='my_channel', body='My message')
    connection.close()