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

AWS EC2部署Node.js应用时Nginx反向代理WebSocket无法连接问题求助

问题排查与修复步骤

1. 核心问题定位

你当前的配置存在3个致命错误:

  • 两个Nginx Server块同时监听80端口且都绑定/路径,配置冲突无法生效
  • WebSocket Upstream配置错误,不需要加ws://前缀
  • 前端调用ws://localhost:9999完全错误:localhost指向访问者本地设备,不是你的EC2服务器,且9999端口未通过Nginx代理、也未开放EC2安全组,必然无法访问

2. 修正Nginx配置

删除你之前单独添加的WebSocket专用Nginx配置文件,直接修改原有80端口的配置文件(存放在sites-available目录下),完整配置如下:

# 升级头映射规则,如果你用Debian/Ubuntu版Nginx,这段也可以单独写到/etc/nginx/conf.d/upgrade.conf中
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # 原有网页服务代理,保持不变
    location / {
        proxy_pass http://localhost:3000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    # 新增WebSocket路径代理,不和根路径冲突
    location /ws {
        proxy_pass http://localhost:9999;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
    }
}

配置修改完成后执行命令验证并生效:

# 验证配置语法是否正确
sudo nginx -t
# 重载Nginx配置
sudo systemctl reload nginx

3. 修正前端调用地址

将前端代码中的WebSocket地址替换为如下格式:

// 把<EC2公网IP>替换为你实际的EC2实例公网IP,如果绑定了域名就用域名
player = new JSMpeg.Player('ws://<EC2公网IP>/ws', {
      canvas: document.getElementById('canvas')
})

4. 额外检查项

  • 确认EC2安全组入站规则开放了80端口,不需要开放9999端口
  • 确认Node.js应用正常运行,EC2本地执行curl http://localhost:9999能正常返回响应,没有端口占用问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:36:00