NGINX returns 502 on WebSocket upgrade when TLS session resumption and upstream keepalive enabled
Environment
Ubuntu 22.04, NGINX 1.22 from official apt repo, TLS terminated on NGINX (client SSL), proxy_pass to upstream Node.js 16.14 (keepalive 32), upstream uses HTTP/1.1 and websockets
Symptoms
WebSocket clients intermittently receive HTTP/1.1 502 Bad Gateway during the Upgrade handshake. Failures happen only after some time of steady traffic; subsequent reconnect succeeds. Normal HTTP(S) requests to same upstream are unaffected.
Observations
NGINX error.log shows: "upstream prematurely closed connection while reading response header from upstream" coinciding with Upgrade requests. Upstream keepalive_pool shows many idle connections. tcpdump shows client TLS handshake resumption from same IP then sudden FIN from upstream; no Node.js errors logged.
Already attempted
Increased proxy_read_timeout, set proxy_http_version 1.1, added proxy_set_header Connection 'Upgrade', toggled keepalive_timeout and reduced keepalive to 8; problem reduced but still occurs. Restarting Node.js clears issue temporarily.
Question
What causes Upgrade (WebSocket) handshakes to get 502 only when TLS session resumption and upstream keepalive are enabled, and how to make NGINX reliably proxy WebSocket Upgrade connections without breaking long-lived TLS resumption or upstream keepalive?
Verified community troubleshooting
First check backend idle timeouts: make Node.js keepAliveTimeout longer than NGINX's proxy_read_timeout so NGINX doesn't reuse a socket the app has already closed. As a quick mitigation, avoid reusing backend sockets for Upgrade by mapping $http_upgrade and forcing Connection: close for non-upgrade flows (so Upgrade gets a fresh backend handshake). Verify by opening a persistent WebSocket and repeatedly reconnecting with TLS session resumption; failures should stop. Roll back by restoring previous keepalive values if new behavior causes load issues and instead enable proxy_next_upstream retry with short keepalive.
Incident analysis
Most likely causes
Summary
Suggested Fixes
Continue troubleshooting
Related troubles
Matched from the title, description and tags
- Servers33% match
Nginx returns 502 Bad Gateway when proxying to local Node.js upstream intermittently
Open0 answers - Cloud Computing31% match
Kubernetes Ingress returns 404 for POST requests only when client uses HTTP/2 to the edge (ingress-nginx misroutes upgraded requests)
Open0 answers - Web Development29% match
Nginx returns 502 for long-lived GraphQL subscription requests only when upstream keepalive is enabled
Solved1 answer - Web Development29% match
Nginx returns 504 Gateway Timeout only for backend requests over ~45s to my Node API
Open1 answer - Web Development28% match
NGINX returns 504 Gateway Timeout for long-running uploads through a Node backend — how to diagnose?
Open1 answer