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

AWS Elastic Beanstalk中Django WebSocket 500握手错误配置求助

解决AWS Elastic Beanstalk Python-Django环境下WebSocket握手500错误

咱们先抓核心问题:WebSocket握手返回500错误,本质是你的Beanstalk环境里的反向代理服务器(Nginx或Apache,取决于环境版本)没配置好WebSocket协议的转发规则。下面分两种常见环境给出具体配置方案:

情况1:你的环境使用Nginx(Amazon Linux 2及以上版本常见)

如果你说找不到/etc/nginx目录,大概率是没通过SSH登录到正确的EC2实例,或者对环境路径不熟悉——没关系,直接通过.ebextensions来注入配置就行:

  1. 在Django项目根目录下创建.ebextensions文件夹(没有的话新建)。
  2. 在该文件夹里新建配置文件01-websocket-proxy.config,内容如下:
files:
  "/etc/nginx/conf.d/websocket.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      # 处理WebSocket协议升级的映射规则
      map $http_upgrade $connection_upgrade {
          default upgrade;
          ''      close;
      }

      server {
          listen 80;

          # 匹配你的WebSocket路径:/xxxxxxxxxx/xxx/ws
          location /xxxxxxxxxx/xxx/ws {
              # 转发到本地8080端口的WebSocket服务
              proxy_pass http://localhost:8080;
              # WebSocket依赖HTTP/1.1,强制启用
              proxy_http_version 1.1;
              # 传递WebSocket升级必需的请求头
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection $connection_upgrade;
              # 传递主机和客户端IP信息给后端服务
              proxy_set_header Host $host;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          }
      }

commands:
  01_restart_nginx:
    command: "systemctl restart nginx"
    ignoreErrors: true
  1. 把这个配置和项目代码一起部署到Elastic Beanstalk即可。

情况2:你的环境使用Apache(旧版Amazon Linux常见)

如果你的环境用的是Apache(能找到/etc/httpd但找不到/etc/nginx),需要先启用WebSocket代理模块再配置转发:

  1. 同样在.ebextensions文件夹下新建01-websocket-proxy.config:
files:
  "/etc/httpd/conf.d/websocket.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      # 启用WebSocket代理模块
      LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so

      # 转发WebSocket请求到本地8080端口
      ProxyPass "/xxxxxxxxxx/xxx/ws" "ws://localhost:8080/xxxxxxxxxx/xxx/ws"
      ProxyPassReverse "/xxxxxxxxxx/xxx/ws" "ws://localhost:8080/xxxxxxxxxx/xxx/ws"

commands:
  01_restart_httpd:
    command: "service httpd restart"
    ignoreErrors: true
  1. 部署代码到Beanstalk完成配置。

额外检查项

  • 确认你的WebSocket服务确实在localhost:8080正常运行:SSH登录EC2实例后,用curl http://localhost:8080/xxxxxxxxxx/xxx/ws测试,只要不返回500或连接失败就没问题。
  • 安全组只需要开放80端口(ws协议默认用80),不需要开放8080——因为是本地转发,外部不会直接访问这个端口。
  • 如果用HTTPS(wss协议),把配置里的ws换成wss、http换成https即可,同时确保Beanstalk已配置SSL证书。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:59:46