nginx logs `upstream prematurely closed connection while reading response header from upstream`.
IntermediateTroubleshootingLoad balancers and reverse proxies
Answer
Likely causes → The upstream accepted the request and then closed the connection without sending a full response: the app worker crashed (OOM, segfault), hit its own timeout (gunicorn --timeout, PHP-FPM request_terminate_timeout), or closed a reused keepalive connection.
Diagnose →
grep 'prematurely closed' /var/log/nginx/error.log | tail
journalctl -u myapp --since '10 min ago' | grep -iE 'killed|timeout|worker'
dmesg -T | grep -i 'out of memory'
Fix → Fix the crash or raise the app's worker timeout above proxy_read_timeout if long requests are legitimate. If it's keepalive-related, raise the upstream's keepalive timeout or set proxy_next_upstream error timeout; for idempotent requests.
Prevent → Align app worker timeouts with proxy timeouts, and alert on worker restarts.
More on Load balancers and reverse proxies
nginx returns `502 Bad Gateway` and the error log says `connect() failed (111: Connection refused) while connecting to upstream`.Beginnernginx returns `504 Gateway Time-out` with `upstream timed out (110: Connection timed out) while reading response header from upstream`.BeginnerAn ALB target group shows all targets `unhealthy` with `Health checks failed with these codes: [404]`.BeginnerAn ALB returns sporadic `502`s, and access logs show `elb_status_code=502` with `target_status_code=-`. Load is low.Intermediatenginx error log shows `no live upstreams while connecting to upstream` and every request gets 502.IntermediateAn NLB shows all targets healthy, but clients from the internet time out connecting through it.Intermediate