Servers

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

Environment

Environment

Nginx 1.22 reverse proxy on Ubuntu 22.04, upstream is Node.js app running on same host on 127.0.0.1:3000 managed by PM2. Nginx proxy_pass configured with keepalive 32 and proxy_http_version 1.1.

Symptoms

Symptoms

Intermittent 502 responses in access logs; Nginx error log shows 'connect() failed (111: Connection refused) while connecting to upstream' occasionally and 'upstream sent invalid header' in other cases. Node logs show occasional restarts during spikes.

Observations

Observations

systemd and PM2 show Node process exit/restart around times of increased traffic. netstat shows many TIME_WAIT/TCP_CLOSE states. Max open file descriptors system-wide seems high but per-process limit for Node may be low.

Already attempted

Already attempted

Increased Nginx proxy_read_timeout and keepalive settings, restarted Nginx, verified that Node's max listeners not exceeded, and temporarily increased PM2 restart delay. Problem recurs under load testing.

Diagnostic steps

Diagnostic steps

  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.
  • What the result means: 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.
  1. 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.
  • What the result means: 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.
  1. Check Node's open file descriptor limit: sudo cat /proc/$(pgrep -f node)/limits and increase PM2/uLimit if low; then repeat load test.
  • What the result means: 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.
  1. 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.
  • What the result means: 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.
Confirmed fixes

Confirmed fixes

No fix has been independently verified for this scenario. Treat the causes below as diagnostic hypotheses.

Question

Question

What is causing intermittent 502s: upstream refusing connections, Nginx keepalive socket reuse issues, or Node process capacity limits? How to diagnose precisely and mitigate without major config churn?

COMMUNITY RESPONSES

Verified community troubleshooting

0 replies

No answers yet..

Showing 0 of 0 community responses
AI DIAGNOSTICS

Incident analysis

Updated 3w ago• Trouble ID

Most likely 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%

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.

Suggested Fixes

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.
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.
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.

Continue troubleshooting

Matched from the title, description and tags