Mastering Docker Compose: Integrating RabbitMQ and Python

In this blog post, we’ll explore how to set up RabbitMQ with Python in a Docker container using Docker Compose. RabbitMQ is a popular message broker that enables your applications to communicate with each other asynchronously. Docker simplifies the process of deploying applications by containerizing them, while Docker Compose allows you to manage multi-container Docker applications.

Prerequisites

Before we start, ensure you have the following installed on your machine:

  • Docker
  • Docker-Compose

Step 1: Set Up Your Project

Create a new directory for your project:

Using following command:

mkdir rabbitmq-python-docker
cd rabbitmq-python-docker

Inside this directory, create a docker compose.yml file and a src directory to hold your Python code.

Step 2: Create the Docker Compose File

The docker-compose.yml file defines the services required for your application. In this case, we’ll define two services one for RabbitMQ and one for our Python application.

So lets create a docker-compose.yml file with the following content.

version: '3'

services:
rabbitmq:
image: rabbitmq:3-management
ports:
  - "15672:15672" # RabbitMQ Management UI
  - "5672:5672" # RabbitMQ Messaging Port

python-app:
  build: ./src
  depends_on:
    - rabbitmq
  volumes:
    - ./src:/app

Step 3: Write the Python Application

Inside the src directory, create a Dockerfile to define the environment for your Python application.

FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

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

Next, create a requirements.txt file to list the dependencies for your Python application. For this example, we’ll use pika, a popular Python library for interacting with RabbitMQ.

Now, create the app.py file with the following content to send and receive messages from RabbitMQ.

import pika
import time

def send_message():
    connection = 
pika.BlockingConnection(pika.ConnectionParameters('rabbitmq'))
    channel = connection.channel()
 
    channel.queue_declare(queue='hello')

    channel.basic_publish(exchange='', routing_key='hello', 
body='Hello World!')
    print(" [x] Sent 'Hello World!'")

    connection.close()

def receive_message():
    connection = 
pika.BlockingConnection(pika.ConnectionParameters('rabbitmq'))
    channel = connection.channel()

    channel.queue_declare(queue='hello')

    def callback(ch, method, properties, body):
        print(f" [x] Received {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__":
   time.sleep(10) # Wait for RabbitMQ server to start
   send_message()
   receive_message()

Related read: Mastering Python Data Analysis: Pandas and Matplotlib Essentials

Transform Your App's Communication with RabbitMQ and Python. Hire Our Developers Now!

Step 4: Build and Run the Application

With your Docker-Compose file and Python application ready, you can now build and run your application.

Run the following command to build and start your Docker containers:

docker-compose up --build

Docker-Compose will pull the RabbitMQ image, build your Python application image, and start the containers. The python-app service will wait for a few seconds to ensure RabbitMQ is fully up and running before sending and receiving messages.

You should see the following output, indicating that your Python application has sent and received a message from RabbitMQ.

python-app_1 | [x] Sent 'Hello World!'
python-app_1 | [*] Waiting for messages. To exit press CTRL+C
python-app_1 | [x] Received b'Hello World!'

Step 5: Access the RabbitMQ Management UI

RabbitMQ comes with a built-in management user interface that you can access to monitor your RabbitMQ server.

  1. Open your browser and navigate to http://localhost:15672.
  2. The default username and password are both guests.
coma

Conclusion

In this blog post, we’ve walked through setting up RabbitMQ with Python in a Docker container using Docker-Compose. This setup allows you to easily manage and deploy your messaging infrastructure, making it more scalable and maintainable.

Feel free to extend this example by adding more complex message handling logic, additional services, or integrating it with other parts of your application. Happy coding!

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?