upstream prematurely closed connection: causes and fixes
Short answer
The backend closed the connection before nginx got the full response. Typical causes: backend crash or self-timeout, mismatched keepalive, a WebSocket not upgraded properly, or backend timeouts on large downloads.
Most common cause: Backend crashed mid-request (OOM, uncaught exception) or PHP's max_execution_time hit.
Try this first: Correct upstream keepalive
upstream app {
server 127.0.0.1:3000;
keepalive 32;
}
location / {
proxy_pass http://app;
proxy_http_version 1.1;
proxy_set_header Connection "";
}Last verified: · against the official docs listed below · Sources
Typical log lines
upstream prematurely closed connection while reading response header from upstream upstream prematurely closed connection while reading upstream
Common causes
- Backend crashed mid-request (OOM, uncaught exception) or PHP's max_execution_time hit.
- upstream keepalive without proxy_http_version 1.1 and Connection "", or backend keepalive timeout shorter than nginx's.
- WebSocket Upgrade/Connection headers not forwarded.
- Gunicorn/uWSGI worker timeout (default 30 s) kills the worker.
Diagnosis commands
journalctl -u your-app -n 100 --no-pagerdmesg -T | grep -i -E 'killed process|oom'curl -sv http://127.0.0.1:3000/path -o /dev/nullFix configs
Correct upstream keepalive
upstream app {
server 127.0.0.1:3000;
keepalive 32;
}
location / {
proxy_pass http://app;
proxy_http_version 1.1;
proxy_set_header Connection "";
}WebSocket
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
location /ws/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 3600s;
}Gunicorn timeout
gunicorn app:app --timeout 120 --workers 3
Run nginx -t first, then systemctl reload nginx.
Key facts and sources
- Proxying WebSocket needs HTTP/1.1 plus the Upgrade / Connection headers; proxy_http_version defaults to 1.1 since nginx 1.29.7, older versions must set it. [nginx.org]
- HTTP upstream keepalive needs proxy_http_version 1.1 (the default since 1.29.7) or 2 and a cleared Connection header; the official example marks both lines as needed only before 1.29.7. [nginx.org]
Checked against the linked pages on 2026-11-14; the official docs win if a newer nginx changes them.
FAQ
Is this an nginx bug?
Almost never. It means the backend hung up first; look in the backend logs.
Do users see a 502 or a broken download?
If the backend drops before the response headers, nginx returns 502; if it drops after they were sent, users get a truncated page or a broken download.
Fix it with a tool
Related errors
VPS / CDN recommendations may appear here later, labelled as affiliate links. There are no referral links today.