FULL AI ANALYSIS

Nginx returns 502 Bad Gateway when proxying to local Node.js upstream intermittently

Generated Nov 1, 2026, 9:47:23 AM

Analysis summary

502s with 'connection refused' indicate Node was not accepting TCP connections when Nginx attempted to connect — likely due to process crash/restart or ephemeral port exhaustion. 'Invalid header' suggests partial or truncated responses (upstream closed socket mid-response). Investigations should check Node crash causes, per-process ulimit, PM2 restart reasons, and TCP TIME_WAIT/ephemeral port exhaustion. Possible mitigations: increase Node process capacity, enable more worker processes, adjust keepalive and proxy settings, or use a unix domain socket with proper permissions.

Possible causes

Node process crashing or restarting under load, leaving a small window for connection refused

8%

Nginx reuses keepalive socket to backend that has been closed, producing invalid header or connection refused

6%

Per-process file descriptor limit (ulimit -n) for Node is too low so backend cannot accept more sockets

6%

Ephemeral port exhaustion or many sockets in TIME_WAIT causing new connections to fail

5%

Suggested fixes

1

Diagnostic step 1

Correlate Nginx error timestamps with Node/PM2 logs and system dmesg: identify if Node crashed near 502 times and capture stack traces or stderr logs. Result meaning: If Node crashed at the same times as 502s, fix the crash cause (OOM, uncaught exception). If Node remained alive, continue to network-level checks.

2

Diagnostic step 2

Monitor socket states: ss -tn state time-wait '( sport = :3000 )' and ss -s to see counts during load. Also check system ephemeral port range and tcp_tw_recycle/timeouts. Result meaning: If TIME_WAIT count is extremely high and ephemeral ports depleted, new TCP connections may fail transiently. Adjust client-side reuse, increase ephemeral range, or use keepalive pooling to reduce churn.

3

Diagnostic step 3

Check Node's open file descriptor limit: sudo cat /proc/$(pgrep -f node)/limits and increase PM2/uLimit if low; then repeat load test. Result meaning: If Node's Max open files is low and the server hits it, the process will fail to accept connections. Raising limit then retesting should reduce or eliminate 502s if FD exhaustion was root cause.

4

Diagnostic step 4

Temporarily switch proxy_pass to a unix domain socket and update Node to listen on that socket; test under load to see if 502s persist. Result meaning: If errors disappear with unix socket, issue is likely TCP socket churn or ephemeral-port related. If errors persist, problem likely with Node process or application-level handling.