【问题标题】:Nginx returns 502 if service not ready on start如果服务在启动时未准备好,Nginx 返回 502
【发布时间】:2016-10-24 00:15:03
【问题描述】:

我正在开发一个使用 Raspberry Pi 构建的网络摄像头。它有以下组件:

  • 3000 端口上的 Node.js
  • FFmpeg / FFserver 在端口 8090
  • 前端的 Nginx 通过端口 80/443 (HTTP/HTTPS) 一起代理这些服务

我遇到的问题是,如果 Nginx 启动时 FFserver 在端口 8090 上没有完全准备好,即使流正在运行,它也会不断地为 stream.mjpeg 返回 502。这就好像 Nginx 确定主机不存在,然后再也不尝试了。一旦我重新启动/重新加载 Nginx 配置,它就会再次开始工作。

为什么会这样?我是否缺少重试条件?

这是 Nginx 的配置:

server {
  listen 80;
  rewrite ^ https://$host$request_uri? permanent;
}

server {
  listen 443 ssl;

  ssl_certificate /etc/nginx/ssl/nginx.crt;
  ssl_certificate_key /etc/nginx/ssl/nginx.key;

  location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_next_upstream error timeout http_502;

    # Basic auth
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/htpasswd;
  }

  location /stream.mjpeg {
    proxy_pass http://localhost:8090/stream.mjpeg;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_next_upstream error timeout http_502;

    # Basic auth
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/htpasswd;
  }
}

【问题讨论】:

  • 如果确实有应用程序在 8090 上提供服务,则不应该发生这种情况。您确认您的应用程序正在运行吗?防火墙问题呢? 8090有什么东西在听吗? (例如netstat -atun | grep 8090 可能会给出一些指示)。作为旁注:您不需要将/stream.mjpeg 附加到您的proxy_pass。 NGINX 会为您执行此操作,因为它位于该位置块中。
  • 我可以通过直接访问该端口来确认服务正在运行。它们确实需要位于不同的位置,因为它们位于不同的端口上。但是,我相信我解决了它,所以请参阅下面的答案。

标签: nginx reverse-proxy ffserver


【解决方案1】:

在查看/var/log/nginx/error.log 的 Nginx 日志后,我可以看到请求将发送到 IPv6 环回地址而不是 IPv4。我将localhost 更改为127.0.0.1,问题得到解决。为什么这在重启 Nginx 后会起作用,但在之前不起作用,对我来说仍然是个谜。

  location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_next_upstream error timeout http_502;

    # Basic auth
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/htpasswd;
  }

【讨论】:

  • 很好地解决了。以前从未见过这个问题,谢谢!
猜你喜欢
  • 2022-08-09
  • 2020-12-22
  • 2021-09-11
  • 1970-01-01
  • 2018-05-05
  • 2014-01-02
  • 2011-01-23
  • 2013-07-14
  • 1970-01-01
相关资源
最近更新 更多