TransWikia.com

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

Server Fault Asked by Antony Gibbs on November 7, 2021

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 ‘keepalive’ connection to the backend ? (for all non websocket requests)

    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?

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

Answered by Michael Hampton on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP