upstream prematurely closed connection while reading response header from upstream
upstream prematurely closed connection while reading upstream
Quick answer: Nginx is fine. Your backend (Node.js, Gunicorn, PHP-FPM, Puma…) accepted the connection and then closed it before sending a complete response, so Nginx returns 502 Bad Gateway. The usual causes, in order:
- The backend's own timeout killed the request. Gunicorn kills a worker after 30 seconds by default; PHP-FPM's
request_terminate_timeoutdoes the same. - The backend process crashed or was OOM-killed in the middle of the request.
- A keepalive mismatch: the backend closed an idle connection at the moment Nginx reused it.
Check the backend's logs at the timestamp of the Nginx error. That tells you which one it is.
What the two variants mean:
- while reading response header: the backend closed before sending any response.
- while reading upstream: the backend started the response and stopped halfway, so the client gets a truncated page.
This is not an Nginx timeout. If Nginx gives up waiting, it logs upstream timed out (110: Connection timed out) instead. Raising proxy_read_timeout doesn't fix "prematurely closed".
1. Did the backend kill its own request? (most common)
If the failing requests are slow ones (reports, exports, large uploads, slow queries) and they fail after a fixed number of seconds, the application server's timeout is ending them.
Gunicorn (Python): the log shows the worker being killed:
[CRITICAL] WORKER TIMEOUT (pid:4821)
The default --timeout is 30 seconds. Raise it for slow endpoints, or better, make the endpoint faster or move the work to a background job:
gunicorn app:app --workers 4 --timeout 120
PHP-FPM: check request_terminate_timeout in your pool file (for example /etc/php/8.3/fpm/pool.d/www.conf) and max_execution_time in php.ini. The FPM log shows execution timed out ... terminating.
Puma / Unicorn (Ruby): look for worker_timeout (Puma) or timeout (Unicorn) in the config.
Rule of thumb: Nginx's proxy_read_timeout (default 60 s) should be at least as long as the backend's timeout. Otherwise you get upstream timed out from Nginx instead. Both should be shorter than any load-balancer timeout in front of Nginx.
2. Did the backend crash or get OOM-killed?
On small servers, the Linux OOM killer often ends the application process when memory runs out:
sudo dmesg -T | grep -iE 'out of memory|killed process'
sudo journalctl -k --since "1 hour ago" | grep -i oom
Killed process 2214 (node) or (gunicorn) at the time of the 502 means the request died with the process. Fix the memory use, add swap, or give the server more RAM.
For other crashes, read the process manager's log around the same timestamp:
pm2 logs --lines 200 # Node.js with PM2
sudo journalctl -u my-app --since "-1h" # systemd service
docker logs --since 1h my-container # Docker
Look for unhandled exceptions, segfaults or restarts.
3. Is it a keepalive mismatch?
If the errors are random, rare, and happen on fast requests, the cause is usually connection reuse. Nginx keeps idle connections to the backend open (when your upstream block has keepalive). If the backend closes an idle connection exactly when Nginx sends a new request on it, Nginx sees the connection drop.
Fix: make the backend keep idle connections open longer than Nginx does.
upstream app {
server 127.0.0.1:3000;
keepalive 32;
keepalive_timeout 60s; # how long Nginx keeps idle upstream connections
}
server {
location / {
proxy_pass http://app;
proxy_http_version 1.1; # required for upstream keepalive
proxy_set_header Connection ""; # required for upstream keepalive
proxy_set_header Host $host;
}
}
Node.js: the default server.keepAliveTimeout is only 5 seconds. Set it above Nginx's upstream keepalive_timeout:
const server = app.listen(3000);
server.keepAliveTimeout = 65_000; // 65 s, longer than Nginx's 60 s
server.headersTimeout = 66_000; // must be larger than keepAliveTimeout
If you don't use upstream keepalive at all, this cause doesn't apply.
4. Test the backend without Nginx
Call the backend port directly on the server, using the same URL that fails:
curl -sv http://127.0.0.1:3000/the/failing/path -o /dev/null
Empty reply from serverorConnection reset by peer: the backend is dropping the connection on its own. Go back to sections 1 and 2.- It works directly but fails through Nginx: compare timeouts and keepalive settings (section 3), and check request size limits on both sides, such as
client_max_body_sizeand the application's own body limit.
After any Nginx change:
sudo nginx -t && sudo systemctl reload nginx
5. Summary table
| What you see | Cause | Fix |
|---|---|---|
Fails after a fixed time on slow requests; WORKER TIMEOUT in Gunicorn log | Backend timeout | Raise the backend timeout, or move the work to a background job |
Killed process … (node/gunicorn) in dmesg | OOM kill | Reduce memory use, add swap or RAM |
| Random, rare 502s on fast requests | Keepalive mismatch | Backend keepalive longer than Nginx's upstream keepalive_timeout |
upstream timed out (110) instead | Nginx timeout (different error) | Raise proxy_read_timeout, or speed up the endpoint |
| Truncated responses (while reading upstream) | Backend crashed or stopped mid-response | Backend logs at that timestamp |
6. Catch the 502s users see
These errors are often intermittent: a few slow requests fail during busy hours, and nobody notices until users complain. An external check on the endpoints that matter shows how often it happens.
With Pingzo, an HTTP monitor calls your URL every 1 to 15 minutes depending on your plan, records the status code and response time, and opens an incident when 3 of the last 5 checks fail. Alerts go to WhatsApp, Slack, Telegram, Discord or email. Watching response times on the same monitor also shows when an endpoint is creeping towards the backend's timeout, before requests start failing.
Related guides
- systemd service keeps restarting: OOM kills and exit code 137
- Nginx "host not found in upstream" in Docker
- Nginx WebSocket reverse proxy (wss://): config and fixes
- Fix: nginx connect() failed (111: Connection refused) while connecting to upstream
- Fix: nginx "upstream sent too big header" (502 Bad Gateway)
Stop Finding Out About Outages from Angry Users
Get instant WhatsApp & Discord alerts the second your API, website, or server goes down. Setup in 30 seconds, with checks as often as every minute.