With two backends in an upstream block, nginx only tries the second one after a connection error or timeout. A backend that answers quickly with a 502 or 503 still gets its error sent to the visitor.
upstream app {
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}
location / {
proxy_pass http://app;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
}
Now a 502 or 503 from one server makes nginx try the next one, and the client never sees the error. With one backend that always returns 502 and another that returns 200, every GET comes back with the 200. proxy_next_upstream_tries 2 caps the attempts, so one bad request cannot walk through ten servers. There is also proxy_next_upstream_timeout for a time limit.
I’d leave http_500 out unless you trust it. A 500 often means the request itself is broken, and then every backend fails on it in turn.
The part people miss: POST, PATCH and LOCK requests are not retried, because retrying them could run an order or a payment twice. A POST gets the 502 straight away, exactly as documented. You can force it with the non_idempotent flag, but only for endpoints that are really safe to run twice. Retries also stop once nginx has started sending the response to the client.
Further reading: proxy_next_upstream
Going deeper: Guide: fix a 502 Bad Gateway in Nginx Proxy Manager, with a checklist that finds the cause