You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Compose部署微服务时RabbitMQ Errno 111连接失败求助

问题排查与解决方案

1. 核心问题:RabbitMQ未完全就绪时Notification服务提前启动

depends_on仅保证容器启动顺序,不确保RabbitMQ服务内部初始化完成(比如认证系统、端口就绪)。Notification启动时RabbitMQ还没准备好,导致连接被拒绝(Errno 111)。

解决方案:

方案A:在Docker Compose中添加启动等待逻辑

修改notification-service的command,先等待RabbitMQ 5672端口就绪再启动服务:

notification-service:
  # ...其他配置
  command: >
    sh -c "until nc -z rabbitmq 5672; do echo Waiting for RabbitMQ...; sleep 2; done; uvicorn main:app --reload --host 0.0.0.0 --port 8000"

注意:需要确保容器内安装了netcat(nc),如果基础镜像没有,要在Dockerfile中添加RUN apt-get update && apt-get install -y netcat-traditional

方案B:在Python代码中添加重试逻辑

在Notification服务的startup事件里增加循环重试,直到连接成功:

import asyncio

@notification.on_event('startup')
async def startup_event():
    max_retries = 15
    retry_interval = 2  # 秒
    for attempt in range(max_retries):
        try:
            connection = await aio_pika.connect_robust(
                host=rabbitmq_host,
                port=rabbitmq_port,
                login=rabbitmq_user,
                password=rabbitmq_password,
                virtual_host='/'  # 显式指定vhost,避免默认值不一致
            )

            channel = await connection.channel()
            await channel.exchange_declare(
                exchange="post",
                exchange_type="direct"
            )
            queue = await channel.declare_queue('post_notify')
            await queue.bind('post', 'post.notify')
            await queue.consume(add_notification)
            print("Consuming messages...")
            break
        except Exception as error:
            print(f"Connection attempt {attempt+1} failed: {error}")
            if attempt < max_retries -1:
                await asyncio.sleep(retry_interval)
            else:
                print("Max retries reached, failed to connect to RabbitMQ")

2. 辅助验证步骤

  • 检查RabbitMQ配置一致性:确认rabbitmq.env中的RABBITMQ_DEFAULT_USER和RABBITMQ_DEFAULT_PASS与代码里的admin/admin123完全匹配。
  • 验证网络连通性:在Notification容器内执行ping rabbitmq和telnet rabbitmq 5672,确认能解析主机名并连通端口。
  • 查看RabbitMQ管理后台:访问http://localhost:15672,用admin账号登录,检查用户权限、vhost配置是否正常,同时查看连接日志是否有异常。

内容的提问来源于stack exchange,提问作者swarna islam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:17:12