Celery + Flask + Docker, consumer: Cannot connect to amqp://admin:**@rabbit:5672/myhost: failed to resolve broker hostname

dmin333

Background

I am building a web application that uses Flask for the backend framework. The application uses Celery to handle all the time-consuming tasks as background tasks as to not block the backend thread. I use RabbitMQ as the message broker for Celery workers. I bundled each service using docker-compose.

Problem

The app has been working well until the past few days, and all of sudden, Celery workers keep failing to connect to the message broker with the error message [ERROR/MainProcess] consumer: Cannot connect to amqp://admin:**@rabbit:5672/myhost: failed to resolve broker hostname.

Directory structure and code

I put together files and directories for minimally reproducible example.

debug/
├── code
│   ├── dev.Dockerfile
│   ├── my_app
│   │   ├── celery_app.py
│   │   ├── config.py
│   │   ├── extensions.py
│   │   ├── __init__.py
│   │   ├── my_tasks.py
│   │   └── test_app.py
│   └── requirements.txt
└── docker-compose_dev.yml

docker-compose_dev.yml

version: "3.7"
services:
  rabbit:
    image: rabbitmq:3.8.5-management
    ports:
      - '15673:15672' # in case user has rabbitMQ installed on host
    expose:
      - "5672"
    environment:
      - RABBITMQ_DEFAULT_USER=admin
      - RABBITMQ_DEFAULT_PASS=mypass
      - RABBITMQ_DEFAULT_VHOST=myhost

  non_working_worker:
    build:
      context: ./code
      dockerfile: dev.Dockerfile
    command: "celery worker -A my_app.celery_app:app -l info"
    volumes:
      - ./code:/code
    links:
      - rabbit

  working_worker:
    build:
      context: ./code
      dockerfile: dev.Dockerfile
    command: "celery worker -A my_app.my_tasks:app -l info"
    volumes:
      - ./code:/code
    links:
      - rabbit

dev.Dockerfile

FROM continuumio/miniconda3

# Make /backend working directory; flask code lives here
WORKDIR /code

# Install from requirements.txt using pip
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
RUN rm requirements.txt

requirements.txt

luigi==2.8.11
plotnine==0.7.0
celery==4.4.6
flask==1.1.2
flask-cors
flask-socketio
Flask-Mail
eventlet

test_app.py

import eventlet
eventlet.monkey_patch()

from flask import Flask
from my_app.extensions import celery

def create_app():
    """
    Application factory. Create application here.
    """
    app = Flask(__name__)
    app.config.from_object("my_app.config")

    return app

def init_celery(app=None):
    """
    Initialize Celery App
    """
    app = app or create_app()
    app.config.from_object("my_app.config")

    # Set celery worker configuration
    # Use this to load config information from flask config file
    celery.conf.broker_url = app.config["CELERY_BROKER_URL"]
    celery.conf.result_backend = app.config["CELERY_RESULT_BACKEND"]

    class ContextTask(celery.Task):
        """Make celery tasks work with Flask app context"""

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask

    return celery

config.py

# RabbitMQ
CELERY_BROKER_URL='pyamqp://admin:mypass@rabbit/myhost'
CELERY_RESULT_BACKEND='rpc://'

extensions.py

from celery import Celery

celery = Celery()

celery_app.py

from my_app.test_app import init_celery

app = init_celery()

my_tasks.py

from celery import Celery


app = Celery()

app.conf.broker_url = 'pyamqp://admin:mypass@rabbit/myhost'
app.conf.result_backend = 'rpc://'

What I've tried

Followings are the things I've tried, but didn't work.

  1. RabbitMQ isn't launching properly?
    • a. It launches properly with given username, password, and vhost. (can check using the management plugin @ localhost:15673)
  2. RabbitMQ launches after the Celery workers start, so the workers can't find the broker?
    • a. Celery has retry feature, so it will keep on retrying until message broker is up running.
  3. Network issue?
    • a. I've tried with/without links to specify service name alias, but still didn't work.
    • b. Note I've already specified broker name as rabbit as specified in the config.py file instead of localhost
    • c. I've tried using both the default network docker-compose creates, and custom network, but both failed.
  4. Interestingly, Celery app instance in my_tasks.py works (it's named as working_worker in the docker-compose file), but Celery app instance in the Flask factory pattern does not work (it'a named as non_working_worker in the compose file)
    • a. Again, it shows that RabbitMQ is working fine, but something funky is going on with the Flask factory pattern style Celery app instantiation.

I spent past few days trying to fix this issue and searching for similar problems on internet, but had no luck doing so.

I know it's a fairly long post, but any help/suggestions would greatly be appreciated.

docker-compose version

docker-compose version 1.25.3, build d4d1b42b
docker-py version: 4.1.0
CPython version: 3.7.5
OpenSSL version: OpenSSL 1.1.0l  10 Sep 2019

docker version

Client: Docker Engine - Community
 Version:           19.03.12
 API version:       1.40
 Go version:        go1.13.10
 Git commit:        48a66213fe
 Built:             Mon Jun 22 15:45:36 2020
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.12
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.10
  Git commit:       48a66213fe
  Built:            Mon Jun 22 15:44:07 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

buena

I had a similar issue that I was able to resolve by specifying the version of dnspython, one of eventlets dependencies, to 1.16.0 in my requirements.txt above eventlet. It looks like eventlet is not compatible with the latest version of dnspython, more info here https://github.com/eventlet/eventlet/issues/619

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Django Celery - Cannot connect to amqp://[email protected]:5672//

Cannot connect to rabbitmq message broker in flask-celery application

Celery in Docker container: ERROR/MainProcess consumer: Cannot connect to redis

WSL: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: Socket closed

consumer: Cannot connect to amqp://user:**@localhost:5672//: [Errno 111] Connection refused

consumer: Cannot connect to amqp://dfmngfek:**@salamander.rmq.cloudamqp.com:5672/dfmngfek: [Errno 104] Connection reset by peer

RabbitMQ Connect Failed: Broker unreachable - Docker image

Restart celery worker consumer connection to broker

Spring AMQP RabbitListener to connect with 2 Rabbit Clusters

PHP cannot resolve hostname

Cannot resolve hostname

Failed to connect to seed broker with kafkajs

Docker doesn't resolve hostname

Celery failing to connect to redis in Flask

MassTransit.RabbitMQ - Connect Failed: Broker unreachable

Application failed unexpectedly Could not connect to amqp

Cannot Connect from Kafkacat running in docker to Kafka broker running locally on windows machine

Spring AMQP Rabbit - single consumer listening to multiple queues - what is the delivery order?

unable to connect to redis with my celery project with rabbitmq as broker

What happens in Sarama library when a consumer tries to connect to a down broker?

AutoSSH cannot resolve hostname directly after boot

tramp mode will not work (ssh cannot resolve hostname)?

docker-compose resolve hostname in url

What if a Kafka broker cannot connect to zookeeper?

Cannot connect to MQTT broker with Eclipse Paho client

Cannot connect to MQTT Broker from ReactJS

Spring application cannot connect to a Kafka broker

kafka consumer try to connect to random hostname instead right one

Cannot connect to ActiveMQ Artemis with AMQP 0.9.1 client

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive