When does nginx return a Bad gateway (502)?

I have an application behind nginx (Rails on Unicorn if it matters)
listens on a UNIX socket.

It all works nice, especially when load is low. When there is some load
the server though (say 70%), I randomly(?) get a bunch of 502 responses

usually in batches.

Thus the question: when (under what conditions) does nginx send a 502

Thanks in advance,


PS: The app’s worker processes do not seem to be irresponsive, slow,
for IO or anything else I have been able to identify as a possible
Thus I want to understand more the nginx side so as to find the root
– which I believe is on the other side (or some config tweak needed

Posted at Nginx Forum:

In my experience, Nginx returns 502 when the upstream server (Unicorn in
your case) doesn’t respond or terminates the connection unexpectedly.


Thank you.

BTW: having googled it for different expressions I’ve found that it is a
well known issue and that it has nothing to do with nginx or the Rails
itself. Unicorn in and of itself can neither be blamed (albeit IMHO
should be some official documentation on this issue, esp. since nginx is
preferred/“official” web server for unicorn). It looks like a socket
backlog setting issue to be handled at OS level but I’m still unsure if
that’s a resolution or not.

Posted at Nginx Forum:

I can confirm that allowing a longer backlog queue (in unicorn config +
net.core.somaxconn and net.core.netdev_max_backlog) did solve the issue

I posted a bit more details at
Bad gateway errors at load on nginx + Unicorn (Rails 3 app) - Stack Overflow.

Posted at Nginx Forum: