Nginx live reverse proxy WebSocket configuration example

  • 2020-05-13 04:33:21
  • OfStack

Implementation scheme

Using the current mature WebSocket technology, the WebSocket protocol provides an option for creating webapp that requires real-time two-way communication between client and server. It is part 1 of HTML5, and WebSocket makes development much simpler than the original app approach. Most current browsers support WebSocket, such as Firefox, IE, Chrome, Safari, Opera, and more and more server frameworks now support WebSocket as well.

WebSocket cluster

In a production environment where multiple WebSocket servers are required to have high performance and high availability, the WebSocket protocol requires a load balancing layer. NGINX supports WebSocket from 1.3, which can be used as a reverse proxy and load balancing for WebSocket applications.

Nginx configuration

Note: according to the official documentation, Nginx does not support websocket reverse proxy until version 1.3, so to use websocket support, you must upgrade to version 1.3

NGINX supports WebSocket by allowing a tunnel to be built between the client and the back-end server. In order for NGINX to send the client Upgrade request to the back-end server, the Upgrade and Connection headers must be set explicitly.

Code example:


upstream wsbackend {
  server 127.0.0.1:8080;
  server 127.0.0.1:8081;
}
server {
  listen  80;
  server_name ws.52itstyle.com;
  location / {
   proxy_pass http://wsbackend;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
  }
}

Front-end configuration:


$(function(){
 socket.init();
});
//Nginx Reverse proxy implementation websocket
var basePath = "ws://ws.52itstyle.com//acts_competition/";
socket = {
 webSocket : "",
 init : function() {
  if ('WebSocket' in window) {
   webSocket = new WebSocket(basePath+'webSocketServer'); 
  } 
  else if ('MozWebSocket' in window) {
   webSocket = new MozWebSocket(basePath+"webSocketServer");
  } 
  else {
   webSocket = new SockJS(basePath+"sockjs/webSocketServer");
  }
  webSocket.onerror = function(event) {
   //alert("websockt Connection error. Please refresh the page and try again !")
  };
  webSocket.onopen = function(event) {
  };
  webSocket.onmessage = function(event) {
    };
 },
 sendData : function(data) {
  webSocket.send(data);
 },
}

Finally, restart Nginx.

Challenges faced by reverse proxy servers in supporting WebSocket

WebSocket is end-to-end, so when a proxy server intercepts an Upgrade request from the client, it needs to send its own Upgrade request to the back-end server, including the appropriate header. Because WebSocket is a long connection, unlike HTTP, which is typically a short connection, the reverse proxy server needs to allow connections to remain open, rather than shutting them down when they seem idle.

conclusion


Related articles: