node.js - nginx + node.js + websockets 的问题
问题描述
我有以下 nginx 配置来在 nginx 反向代理后面运行带有 websockets 的 node.js:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
gzip on;
upstream nodejsserver {
server 127.0.0.1:3456;
}
server {
listen 443 ssl;
server_name myserver.com;
error_log /var/log/nginx/myserver.com-error.log;
ssl_certificate /etc/ssl/myserver.com.crt;
ssl_certificate_key /etc/ssl/myserver.com.key;
location / {
proxy_pass https://nodejsserver;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 36000s;
}
}
}
node.js 服务器使用与 nginx 配置中指定的相同的证书。
我的问题是在我的浏览器中(Firefox,虽然这个问题也出现在其他浏览器中),我的 websocket 连接每隔几分钟就会重置一次,代码为 1006。我已经研究了这个特定(或类似)星座中这个错误的原因,这里的大多数答案以及其他资源都指向proxy_read_timeout
nginx 配置变量未设置或设置太低。但在我的配置中并非如此。
值得一提的是,当我运行 node.js 并直接访问它时,无论在本地还是在服务器上,我都不会遇到这些断开连接的情况。
此外,我尝试不安全地运行 nginx 和 node.js(端口 80),并在我的客户端中访问 ws:// 而不是 wss://。问题仍然相同。
解决方案
您需要做一些事情来保持连接处于活动状态。
您应该为每个工作进程建立一个 keepalive连接计数,并且文档说明您还需要明确说明您的协议。除此之外,您可能会遇到其他类型的超时,因此请编辑您的上游和服务器块:
upstream nodejsserver {
server 127.0.0.1:3456;
keepalive 32;
}
server {
#Stuff...
location / {
#Stuff...
# Your time can be different for each timeout, you just need to tune into your application's needs
proxy_read_timeout 36000s;
proxy_connect_timeout 36000s;
proxy_send_timeout 36000s;
send_timeout 36000s; # This is stupid, try a smaller number
}
}
SO中有许多关于同一主题的其他讨论,请查看此答案
推荐阅读
- c# - 如何在 C# 中重用查询
- javascript - 如何修改此代码以不要求文件。[JavaScript]
- python - sys.stdin.readline().split() 排序时,整数序列很奇怪
- javascript - 在 javascriot 中使用 Select 的计算器
- reactjs - 如何在 Redux-Toolkit 中改变 asyncThunk 挂起状态的状态?
- python - pyspark:数据帧头转换
- angularjs - 如何知道 Web 应用程序是在浏览器上访问还是从团队自定义应用程序访问
- c++ - Google 测试 (gtest) `EXPECT_TRUE()` 宏不会以 `std::is_same<>` 模板作为输入进行编译
- elasticsearch - json数据有方括号logstash如何解释它?
- python - 你如何更新表以适应新列?