Search code examples
pythondjangodockerrabbitmqcelery

How to connect celery to rabbitmq in django from docker


I learn docker and don't understand why celery can't connect to rabbitmq. I've created 2 images for rabbitmq and django, here is my docker-compose:

version: "3.0"

services:
  # WEB
  django:
    build: .
    volumes:
      - media_volume:/website/journal_website/media
      - static_volume:/website/journal_website/static
      - database_volume:/website/journal_website/database
    ports:
      - "8000:8000"
    depends_on:
      - rabbit
  
  # RabbitMQ
  rabbit:
    hostname: rabbit
    container_name: rabbitmq
    image: rabbitmq:3.12-rc-management
    environment:
      - RABBITMQ_DEFAULT_USER=simple_user
      - RABBITMQ_DEFAULT_PASS=simple_password
    ports:
      # AMQP protocol port
      - "5672:5672"
      # HTTP management UI
      - "15672:15672"
    restart: always
      

volumes:
  media_volume:
  static_volume:
  database_volume:

my broker configuration in settings.py in django:

CELERY_BROKER_URL = 'amqp://localhost:5672'

celery.py file:

from __future__ import absolute_import, unicode_literals
import os

from celery import Celery


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings")
celery_application = Celery("website")
celery_application.config_from_object("django.conf:settings", namespace="CELERY")
celery_application.autodiscover_tasks()

entrypoint.sh that's used as entrypoint in Dockerfile:

#!/bin/bash

# Start Celery
celery -A website worker -l info

# Run Django server
python3.11 manage.py runserver 127.0.0.1:8000

and Dockerfile:

# Many many commands to install python and all dependencies in ubuntu 20.04

# Run Django server
EXPOSE 8000
ENTRYPOINT ["/entrypoint.sh"]

I use Docker Desktop on Windows 10, when I run docker compose up or run container in desktop application I get such error: [Date: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused., I've checked that localhost is 127.0.0.1. What should I do to run celery properly?


Solution

  • Probably you have to change your url to: amqp://rabbit:5672