Error: upstream prematurely closed connection while reading response header from upstream [uWSGI/Django/NGINX] Error: upstream prematurely closed connection while reading response header from upstream [uWSGI/Django/NGINX] nginx nginx

Error: upstream prematurely closed connection while reading response header from upstream [uWSGI/Django/NGINX]


This is unlikely to be an nginx config issue.

It's almost certainly that the backend is actually crashing (or just terminating the connection) rather than giving a malformed response. i.e. the error message is telling you what the problem is, but you're looking in the wrong place to solve it.

You don't give enough information to allow use to figure out what the exact issue is but if I had to guess:

which usually returns 872 rows and takes 2.07 to run in MySQL. It is however returning a LOT of information.

It's either timing out somewhere or running out of memory.


I had the same issue, what fixed it for me is adding my domain in the settings.py e.g.:

ALLOWED_HOSTS = ['.mydomain.com', '127.0.0.1', 'localhost']

By same issue, I mean I couldn't even load the page, nginx would return a 502 without serving any pages where I could cause the application to crash.

And the nginx log contained:

Error: upstream prematurely closed connection while reading response header from upstream


In your @django location block you can try adding some proxy read and connect timeout properties. e.g.

location @django {   proxy_read_timeout 300;   proxy_connect_timeout 300;   proxy_redirect off;   # proxy header definitions   ...   proxy_pass http://django;}