Nginx proxy websocket: is it required to close the connection to backend after upgrading to a websocket?

Antony Gibbs asked:

Base on what I could read on nginx site
https://www.nginx.com/blog/websocket-nginx/

The exemple they give will close all connections to backend. This isn’t really what we want on a proxy setup, forcing to reopen a connection to backend on each new client.

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }
 
    upstream websocket {
        server 192.168.100.10:8010;
    }
 
    server {
        listen 8020;
        location / {
            proxy_pass http://websocket;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header Host $host;
        }
    }
}

But is it required to close the connection after upgrading to a websocket?

can’t we change the map so it maintains the connection to the backend ?

    map $http_upgrade $connection_upgrade {
        default upgrade;
#       ''      close;
        ''      '';
    }

Being the only user on a test environment it didn’t seem to create any issues, but will it be the same in production?

My answer:


This map does not cause websocket connections to close.

What it actually does is check whether the Upgrade: request header contains any value. If it does, then it returns upgrade, which is then passed upstream as the header Connection: upgrade.

It only returns close when the Upgrade: request header is missing. This should not happen in normal operation, but if it does happen, then you can’t reliably (or at all) establish a websocket connection to the browser anyway.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.