我正在将一个 node.js 应用程序从 Heroku 迁移到在端口 80 上使用 WebSockets 的 AWS Elastic Beanstalk。WebSockets 在 AWS Elastic Beanstalk 上返回 301 错误,但在 Heroku 上没有。
要初始化 WebSocket 连接,请单击创建新笔记
。
AWS bean 茎 http://default-environment.psgekxtsbd.us-west-2.elasticbeanstalk.com/
英雄联盟 https://murmuring-shelf-40601.herokuapp.com/
这就是我在服务器上设置 WebSockets 的方式。
const express = require('express');
const app = express();
require("express-ws")(app);
app.post("/service/create-account/", (req, res)=> {/*code in here*/});
app.ws('/:noteId/', function (ws, req) {/*code in here*/});
const port = process.env.PORT || 3000;
app.listen(port);
我尝试在 .ebextensions
文件夹中添加不同的配置,例如,
files:
"/etc/nginx/conf.d/01_websockets.conf" :
mode: "000644"
owner: root
group: root
content : |
upstream nodejs {
server 127.0.0.1:80;
keepalive 256;
}
server {
listen 80;
large_client_header_buffers 8 32k;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
# prevents 502 bad gateway error
proxy_buffers 8 32k;
proxy_buffer_size 64k;
proxy_pass http://nodejs;
proxy_redirect off;
# enables WS support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
和
files:
"/etc/nginx/conf.d/websocketupgrade.conf" :
mode: "000755"
owner: root
group: root
content: |
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
当我添加这些配置时,HTML 加载失败并出现错误 ERR_NAME_NOT_RESOLVED
。这是 URL http://websocketsissue.us-west-2.elasticbeanstalk.com/
我使用 Node.js 的预定义配置将我的弹性 beanstalk 环境设置为 Web 服务器环境。我没有添加任何额外的资源。
有没有办法使用 AWS Elastic Beanstalk 让 WebSockets 在端口 80 上工作?
更新
我能够使单实例环境正常工作,但不能使负载平衡的自动缩放环境正常工作。
为了让单个实例工作,我将以下文件添加到 .ebextensions
container_commands:
01_nginx_websocket_support:
command: |
sed -i '/\s*proxy_set_header\s*Connection/c \
proxy_set_header Upgrade $http_upgrade;\
proxy_set_header Connection "upgrade";\
' /tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf
最佳答案
我在 .ebextensions
文件夹中添加了一个包含以下内容的文件,并针对单实例环境对其进行了修复。
container_commands:
01_nginx_websocket_support:
command: |
sed -i '/\s*proxy_set_header\s*Connection/c \
proxy_set_header Upgrade $http_upgrade;\
proxy_set_header Connection "upgrade";\
' /tmp/deployment/config/#etc#nginx#conf.d#00_elastic_beanstalk_proxy.conf
为了让 WebSockets 在负载均衡、自动缩放的环境中工作,我还需要执行以下操作
- 转到 EC2 仪表板
- 找到 Elastic Beanstalk 项目创建的负载均衡器
- 右键单击负载均衡器,然后单击“编辑监听器”
- 将端口 80 的负载均衡器协议(protocol)从 HTTP 更改为 TCP 并保存更改
关于node.js - 使用端口 80 的 AWS Elastic Beanstalk 上的 WebSocket 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43793853/