Node.js 带ALB的AWS Elastic Beanstalk:节点Websocket超时
我已经阅读了几篇博客文章,并按照他们的说明,介绍了如何使用应用程序负载平衡器(ALB)让节点WebSocket与AWS Elastic Beanstalk(EB)一起工作,但毫无效果 本地使用时,应用程序可与WebSocket一起正常工作(Node.js 带ALB的AWS Elastic Beanstalk:节点Websocket超时,node.js,amazon-web-services,amazon-ec2,websocket,amazon-elastic-beanstalk,Node.js,Amazon Web Services,Amazon Ec2,Websocket,Amazon Elastic Beanstalk,我已经阅读了几篇博客文章,并按照他们的说明,介绍了如何使用应用程序负载平衡器(ALB)让节点WebSocket与AWS Elastic Beanstalk(EB)一起工作,但毫无效果 本地使用时,应用程序可与WebSocket一起正常工作(localhost) 在EB中,应用程序正确加载并显示在浏览器中,但Websocket无法连接并最终超时 WebSocket connection to 'ws://tradey-12-hr-dev.ap-northeast-1.elasticbeanstal
localhost
)
在EB中,应用程序正确加载并显示在浏览器中,但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的后端代码。BE和FE中使用的端口均为3030
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行日志的链接。没有生成任何错误:
我希望这是一件小事,我的直觉告诉我,我必须允许通过安全组或其他方式将流量传输到端口3030
——我甚至在所有安全组上创建了新的入站流量规则,允许来自“任何地方”的流量,但这也不起作用(见附图)
提前感谢您的帮助=)
我想出来了。ALB只支持HTTP,不支持TCP。真正的WebSocket(例如npm ws-library)运行在TCP上,因此它们不能与ALB一起工作。您可以将真正的WebSocket与ELB一起使用,也可以使用类似Socket.io与ALB的长轮询的库。我写了一篇完整的博客文章,你可以在这里阅读: