【问题标题】:Issues with nginx + node.js + websocketsnginx + node.js + websockets 的问题
【发布时间】:2018-08-21 21:42:00
【问题描述】:

我有以下 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://。问题依旧。

【问题讨论】:

    标签: node.js nginx websocket


    【解决方案1】:

    您需要做一些事情来保持连接处于活动状态。

    您应该建立一个keepalive connection count per worker proccess,并且文档指出您还需要明确说明您的协议。除此之外,您可能会遇到其他类型的超时,因此请编辑您的上游和服务器块:

    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 中还有许多关于同一主题的其他讨论,check this answer out

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 2013-03-27
      • 2011-03-28
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多