Solving problems with WebSockets

WebSockets are a modern protocol that allows a web application to have persistent, duplex, long-living connections to servers, similar to real TCP connections (and they are, under the hood, pretty normal TCP connections).

WebSockets use the special URL scheme ws:// (or wss:// for secure), and you will see that in your browser error console if you try to run a WebSocket-opening web application from an Nginx-powered server.

The philosophy behind WebSockets directly conflicts with the buffered-reverse proxy idea that is the foundation of Nginx as a web accelerator. See the previous chapter for the comprehensive introduction into what makes Nginx fast. Fortunately, modern Nginx is so much more than just a simple reverse proxy. It has so much to offer that even without the buffering and cheap connection pools, it is too valuable to ditch because of WebSockets. And since version 1.3.13, which was released almost 3 years ago, in early 2013, Nginx has had special support to create long-living tunnels between the client and the server, which was specifically introduced to support WebSockets.

To enable upgrading a normal HTTP connection to a WebSocket, you have to do this:

    proxy_pass http://localhost:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_read_timeout 1000s;

You should appreciate how the support was introduced without a single new directive. The configuration language is already rich enough for this. The magic happens due to the Upgrade: header sent by the client and the 101 Switching Protocols HTTP response code from the server.

One very important parameter is the timeout specified with the proxy_read_timeout method. The default value of 1 minute might not be sufficient for your (and most other) WebSocket use cases. The whole idea of direct long-living connections between the app in the browser and the server may be defeated by a short proxy timeout. It is perfectly normal for a WebSocket connection to be idle for long periods of time, and this is the reason for the increased timeout value. The other solution is implementing some sort of heartbeats or pings between the sides of the connection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.0.85