【问题标题】:Why is my NGINX to pm2 upstream slow when restarting?为什么重新启动时我的 NGINX 到 pm2 上游速度很慢?
【发布时间】:2021-05-03 20:55:56
【问题描述】:

我使用 nginx 反向代理到上游的 Node.js/PM2 运行家庭服务器。通常它工作得很好。但是,当我想进行更改时,我会运行 pm2 reload pnamepm2 restart pname,这会导致 nginx 在找到新的上游之前抛出 502 Bad Gateway 大约 10-20 秒。

我的 Node.js 应用程序启动速度非常快,我 99% 确信上游启动并绑定到端口实际上不会花费那么长时间(当我不使用 nginx 层时,它可以立即访问)。如何消除 nginx 解决问题所需的额外时间?

来自 nginx/error.log:

2021/01/29 17:50:35 [error] 18462#0: *85 no live upstreams while connecting to upstream, client: [ip], server: hostname.com, request: "GET /path HTTP/1.1", upstream: "http://localhost/path", host: "www.hostname.com"

来自我的 nginx 域配置:

server {
        listen 80;
        server_name hostname.com www.hostname.com;
        return 301 https://$host$request_uri;
}

server {
        listen 443 ssl;
        server_name hostname.com www.hostname.com;
        # ...removed ssl stuff...
        gzip_types      text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
        gzip_proxied    no-cache no-store private expired auth;
        gzip_min_length 1000;
        location /  {
                proxy_pass    http://localhost:3010;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
                proxy_set_header X-Forwarded-For $remote_addr;
                proxy_read_timeout 240s;
        }
}

【问题讨论】:

  • 我观察到我们的 nginx/node 组合的类似行为。虽然工作人员会在几秒钟内快速重启,但对我们前端的请求会迟缓一分钟左右,直到一切恢复正常。我们已经尝试手动告诉 nginx 在重新启动期间有一个工作人员已关闭,但它没有帮助。会对解决方案感兴趣。
  • 您是否尝试过在节点工作程序重新启动后立即弹回您的 ngnix 服务器?如果您使用的是 Ubuntu,请使用 sudo systemctl restart nginx
  • 查看server directive 上的fail_timeout 选项,它似乎描述了您遇到的行为。

标签: node.js nginx pm2


【解决方案1】:

这是由上游的默认行为引起的,这可能并不明显,因为您没有使用 upstream 指令明确声明您的上游。带有upstream 指令的配置如下所示:

upstream backend {
        server localhost:3010;
}

...

server {
        listen 443 ssl;
        ...
        location /  {
                proxy_pass    http://backend;
                ...
        }
}

在这种形式中,很明显您只是依赖server 指令的默认选项。 server 指令有很多选项,但其中两个在这里很重要:max_failsfail_timeout。这些选项控制故障状态以及 nginx 应该如何处理它们。默认情况下max_fails=1fail_timeout=10 seconds,这意味着在尝试与上游 nginx 通信失败后,将等待 10 秒再尝试。

要在您的环境中避免这种情况,您可以通过设置 max_fails=0 来禁用此机制:

upstream backend {
        server localhost:3010 max_fails=0;
}

【讨论】:

    猜你喜欢
    • 2019-12-03
    • 2022-10-22
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    相关资源
    最近更新 更多