Docker集成RabbitMQ报错:connect ECONNREFUSED 192.168.80.2:5672
解决RabbitMQ连接被拒绝(ECONNREFUSED)的问题
问题现象
执行docker compose up -d --build后,gateway服务日志出现以下错误:
Error: connect ECONNREFUSED 192.168.80.2:5672 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1229:16) { errno: -111, code: 'ECONNREFUSED', syscall: 'connect', address: '192.168.80.2', port: 5672 }
当前Docker Compose配置
message_broker: image: rabbitmq:3.10-management-alpine hostname: rabbitmq restart: unless-stopped volumes: - message_broker_data:/var/lib/rabbitmq ports: - 15672:15672 networks: - tms gateway: container_name: gateway stdin_open: true tty: true build: context: ./micro_services/gateway dockerfile: Dockerfile depends_on: - storage volumes: - ./micro_services/gateway/src/:/app/src/ - ./micro_services/gateway/public/:/app/public/ - tms_logs:/var/log/gateway environment: PORT: 3000 STORAGE_URL: 'http://storage:3000' LOGS_PATH: '/var/log/gateway' ports: - '3000:3000' networks: - tms
RabbitMQ连接代码片段
module.exports = async () => { try { const queue = 'tasks' const conn = await amqplib.connect('amqp://message_broker:5672')
解决方案
补充服务依赖关系
gateway服务需要连接message_broker,但当前depends_on只声明了storage,需要把message_broker添加进去:gateway: # 其他配置... depends_on: - storage - message_broker注:
depends_on仅保证容器启动顺序,不保证RabbitMQ服务完全就绪,需配合就绪检查使用。添加RabbitMQ健康检查
给message_broker配置健康检查,确保RabbitMQ服务启动完成后再启动gateway:message_broker: # 其他配置... healthcheck: test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] interval: 5s timeout: 5s retries: 5同时修改gateway的
depends_on,依赖message_broker的健康状态:gateway: # 其他配置... depends_on: storage: condition: service_started message_broker: condition: service_healthy验证网络连通性
如果问题仍存在,可进入gateway容器测试与RabbitMQ的连通性:# 进入gateway容器 docker exec -it gateway sh # 测试DNS解析 ping message_broker # 测试端口连通 telnet message_broker 5672若解析或连通失败,检查两个服务是否都在
tms网络中,确保网络配置无误。添加连接重试逻辑(可选)
在代码中加入重试机制,避免因服务启动时差导致的连接失败:const amqplib = require('amqplib'); module.exports = async () => { const queue = 'tasks'; let conn; const maxRetries = 5; let retries = 0; while (!conn && retries < maxRetries) { try { conn = await amqplib.connect('amqp://message_broker:5672'); console.log('成功连接到RabbitMQ'); break; } catch (err) { retries++; console.log(`连接失败,重试第${retries}次...`); await new Promise(resolve => setTimeout(resolve, 2000)); } } if (!conn) { throw new Error('多次重试后仍无法连接到RabbitMQ'); } // 后续业务逻辑... };
内容的提问来源于stack exchange,提问作者Radomir
相关产品推荐
相关产品推荐

