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

Docker容器中FastAPI无法连接RabbitMQ的问题求助

解决Docker容器中FastAPI连接本地RabbitMQ的ConnectionError问题

问题根源:你的FastAPI代码中使用localhost连接RabbitMQ,但Docker容器的localhost指向容器自身的网络栈,而非宿主机。你在本地通过brew启动的RabbitMQ运行在宿主机上,因此容器无法通过localhost访问到它,导致[Errno 111] Connect call failed错误。

方案1:使用Docker宿主机特殊域名(推荐macOS)

Docker for macOS提供了host.docker.internal这个特殊域名,专门用于容器访问宿主机上的服务。修改你的RabbitMQ连接地址即可:

修改代码中的连接字符串

找到send_rabbitmq函数里的连接代码,将localhost替换为host.docker.internal:

async def send_rabbitmq(msg = {}):
    # 替换localhost为host.docker.internal
    connection = await connect("amqp://guest:guest@host.docker.internal/")

    channel = await connection.channel()

    await channel.default_exchange.publish(
        Message(json.dumps(msg.dict()).encode("utf-8")),
        routing_key = "fastapi_task"
    )

    await connection.close()

重新构建并运行容器

修改代码后,重新构建镜像并启动容器:

docker build -t image_name .
docker run -p 80:80 image_name

方案2:确保RabbitMQ监听所有网络接口

如果host.docker.internal无法使用,需要确保RabbitMQ不是仅监听127.0.0.1(本地回环地址),而是监听所有接口:

  1. 查看RabbitMQ当前监听地址:
lsof -i :5672

如果输出中只有127.0.0.1:5672,说明仅本地可访问。

  1. 修改RabbitMQ配置:
    找到RabbitMQ的配置文件(macOS下通常在/usr/local/etc/rabbitmq/rabbitmq.conf),添加或修改以下配置:
listeners.tcp.default = 0.0.0.0:5672
  1. 重启RabbitMQ服务:
brew services restart rabbitmq
  1. 使用宿主机IP连接:
    在FastAPI代码中,将localhost替换为你的宿主机实际IP(比如192.168.1.100):
connection = await connect("amqp://guest:guest@192.168.1.100/")

验证连接

修改完成后,调用/AddTasks接口,应该能成功连接RabbitMQ并发送消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:27:17