Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use nginx as websocket proxy?

So I've been reading up on this whole server set up in which Nginx is used in front of nodejs as a reverse proxy so that it serves the static content while allowing node to do the dynamic stuff. My question is, why would someone want to use the nginx front to reverse proxy to the websocket? If nginx serves the static content (HTML, CSS, JS, media, etc.) then can't the JS file that is served simply connect to the server directly using the ip address and the port that the websocket is listening on in the nodejs server? Why go through nginx to connect to the websocket on the server? Or am I not understanding this situation clearly? Thank you!

like image 812
TheMAAAN Avatar asked Jul 27 '16 18:07

TheMAAAN


1 Answers

A WebSocket application keeps a long-running connection open between the client and the server, facilitating the development of real-time applications. The HTTP Upgrade mechanism used to upgrade the connection from HTTP to WebSocket uses the Upgrade and Connection headers. There are some challenges that a reverse proxy server faces in supporting WebSocket. One is that WebSocket is a hop-by-hop protocol, so when a proxy server intercepts an Upgrade request from a client it needs to send its own Upgrade request to the backend server, including the appropriate headers. Also, since WebSocket connections are long lived, as opposed to the typical short-lived connections used by HTTP, the reverse proxy needs to allow these connections to remain open, rather than closing them because they seem to be idle.

NGINX supports WebSocket by allowing a tunnel to be set up between a client and a backend server. For NGINX to send the Upgrade request from the client to the backend server, the Upgrade and Connection headers must be set explicitly, as in this example:

location /wsapp/ {
    proxy_pass http://wsbackend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Once this is done, NGINX deals with this as a WebSocket connection.

For more details please visit:- https://www.nginx.com/blog/websocket-nginx/ https://blog.martinfjordvald.com/2013/02/websockets-in-nginx/

Hope this would help!

like image 196
Parveen yadav Avatar answered Sep 25 '22 03:09

Parveen yadav