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

Docker容器(NGINX/Node.js)内部通信异常:Ping正常但浏览器报504超时

Nginx容器与Node.js后端容器通信504超时问题排查

问题描述

Docker环境下,Nginx容器与Node.js后端容器处于同一自定义网络,命令行ping其他容器正常,但浏览器访问localhost时返回504 Gateway Time-out错误。

配置文件

docker-compose.yml

version: '3'

services:
    nodejs-app:
        build:
          context: ./nodedocker_app
        container_name: nodejsserver
        hostname: nodejsserver
        ports:
            - "3000:3000" 
        networks:
            - example-net
        depends_on:
            - mongo
    mongo:
        container_name: mongo
        image: mongo
        volumes:
            - ./data:/data/db
        ports:
            - "27017:27017" 
        networks:
            - example-net 
    nginx:
        build:
          context: ./nginx
        container_name: nginx
        hostname: nginx
        ports:
            - "80:80" 
        depends_on:
            - nodejs-app
        networks:
            - example-net

networks:
  example-net:
    external: true

default.conf(Nginx)

server {
  location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://nodejsserver:3000;
  }
}

解决方案

  • 修正Node.js应用监听地址
    确保Node.js应用监听0.0.0.0而非默认的127.0.0.1,否则仅容器内部可访问,同一网络的Nginx容器无法连接。修改启动代码:

    app.listen(3000, '0.0.0.0', () => {
      console.log('服务运行在端口3000');
    });
    
  • 解决容器启动顺序问题
    depends_on仅保证Node.js容器先启动,不保证应用完成初始化。可在Nginx容器启动时添加等待逻辑,确保Node.js服务可用:
    在Nginx的Dockerfile中添加:

    RUN apt-get update && apt-get install -y curl
    CMD ["sh", "-c", "until curl -s http://nodejsserver:3000; do sleep 1; done && nginx -g 'daemon off;'"]
    
  • 检查Node.js容器运行状态
    执行docker logs nodejsserver查看应用日志,排查是否有启动报错、数据库连接失败等问题导致服务无法响应请求。

  • 验证网络配置
    执行docker network inspect example-net,确认所有容器都已加入example-net网络,且容器名称/hostname可被正常解析。

内容的提问来源于stack exchange,提问作者Manas S. Roy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:50:22