简体   繁体   中英

Nginx returns 502 if service not ready on start

I'm working on a webcam I built with a Raspberry Pi. It has these components:

  • Node.js on port 3000
  • FFmpeg / FFserver on port 8090
  • Nginx in front to proxy these services together over ports 80/443 (HTTP/HTTPS)

The problem that I am having is that if FFserver is not fully ready on port 8090 when Nginx starts up it will continually return a 502 for stream.mjpeg , even though the stream is running. It's as if Nginx determines that the host does not exist and then never tries again. Once I restart/reload the Nginx config it starts working again.

Why does this happen? Is there a retry condition I am missing?

Here is the config for 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;
  }
}

After reviewing the Nginx logs at /var/log/nginx/error.log I could see that the requests were going to the IPv6 loopback address and not the IPv4. I changed localhost to 127.0.0.1 and the issues were resolved. It's still a mystery to me as to why this would work after restarting Nginx but not before.

  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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM