Video in progress

WebSocket works locally, but behind Nginx the handshake fails or the connection drops after 60 seconds. What is the cause?

By default Nginx doesn't forward the Upgrade and Connection hop-by-hop headers to the backend and uses HTTP/1.0, so the upgrade never happens. The 60-second drop is the default proxy_read_timeout: if there's no traffic on the connection, Nginx closes it.

📖 Answer

The correct configuration:

location /ws {
    proxy_pass http://app:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_read_timeout 1h;
    proxy_send_timeout 1h;
}

Why each line is there:

  • proxy_http_version 1.1: the upgrade mechanism exists in HTTP/1.1;
  • Upgrade and Connection: they are hop-by-hop headers, Nginx drops them itself, so you have to forward them explicitly;
  • proxy_read_timeout: the default is 60s. It's a wait time, not the total lifetime of the connection: every frame that arrives resets the counter.

Instead of raising proxy_read_timeout to 24 hours, I prefer to add an application heartbeat (say every 25 seconds). Then the connection survives even with the timeout left at 60s, and truly dead connections are cleaned up quickly.

The same problems exist on AWS ALB, Cloudflare and other proxies; each has its own idle timeout.