How to configure nginx to hold the connections and retry if the proxied server returns 502?

I have a NodeJS app that sometimes sends 502 status code when the app is rebooting. Nginx is configured as a reverse proxy and as a result nginx also returns 502.

How do I setup Nginx so that it retries and forwards the connection to backend proxied server 2-3 times in case of 502 responses?

Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown 路 Publish articles on custom domain 路 Gain readership on day zero 路 Automatic GitHub backup and more

Comments (1)

Adam Listek's photo

As best as I can tell, I think you want to do something like this:

upstream node_js_servers { 
    server backup;

server {
    proxy_next_upstream error timeout http_502;
    proxy_pass         http://my_upstream;

What the following should do is go to the next upstream server on error or timeout and the "backup" tells NGINX to only use that server in the event the other is not available. Of course, you can add more servers there and use the default round-robin approach to load-balancing if you would like. I haven't tested this, so test first. Good luck!