node.js - AWS Elastic Beanstalk 与 ALB:节点 Websocket 超时
问题描述
我已经阅读了几篇博客文章,并按照他们关于如何使用 Application Load Balancer (ALB) 让 Node Websockets 与 AWS Elastic Beanstalk (EB) 一起工作的说明进行操作 - 无济于事。
应用程序在本地使用时可与 Websocket 一起正常工作 ( localhost
)。
在 EB 中,App 正常加载并在 Browser 中显示,但 Websocket 没有连接并最终超时。
WebSocket connection to 'ws://tradey-12-hr-dev.ap-northeast-1.elasticbeanstalk.com:3030/' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
根据博客文章,我在我的应用程序中添加了以下内容.ebextensions/enable-websockets.config
:
container_commands:
enable_websockets:
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
这是设置 websocket 的后端代码。使用的端口3030
在 BE 和 FE 中。
import WebSocket from 'ws'
const setUpWebsocketServer = port => new WebSocket.Server({ port })
export default setUpWebsocketServer
这是启动握手的前端代码:
const target = window.location.host === 'localhost:3000' ?
'localhost' : window.location.host
const ws = new WebSocket(`ws://${target}:${PORT}`)
这是最后 100 行日志的链接。没有产生错误:
https://gist.github.com/bengrunfeld/e2f46e3575a3f57a68ed3c39fd63e7d8
我希望这是一件小事,我的直觉告诉我,我必须允许流量3030
通过安全组或其他东西进行端口 - 我什至在所有安全组上创建了新的入站流量规则,允许来自“任何地方”的流量,但这也是没有工作(见附图)。
提前感谢您的帮助=)
解决方案
我想到了。ALB 只支持 HTTP,不支持 TCP。真正的 Websockets(例如 npm ws 库)通过 TCP 运行,因此它们不能与 ALB 一起使用。您可以将真正的 Websockets 与 ELB 一起使用,也可以使用像 Socket.io 与 ALB 一样回退到长轮询的库。我写了一篇关于它的完整博客文章,你可以在这里阅读:https ://medium.com/@binyamin/node-websockets-with-aws-elastic-beanstalk-elastic-load-balancer-elb-or-application -load-6a693b21415a