https://www.nginx.com/blog/websocket-nginx/

 

NGINX as a WebSocket Proxy

The WebSocket protocol provides a way of creating web applications that support real‑time bidirectional communication between clients and servers. Part of HTML5, WebSocket makes it much easier to develop these types of applications than the methods previously available. Most modern browsers support WebSocket including Chrome, Firefox, Internet Explorer, Opera, and Safari, and more and more server application frameworks are now supporting WebSocket as well.

For enterprise production use, where multiple WebSocket servers are needed for performance and high availability, a load balancing layer that understands the WebSocket protocol is required, and NGINX has supported WebSocket since version 1.3 and can act as a reverse proxy and do load balancing of WebSocket applications. (All releases of NGINX Plus also support WebSocket.)

Check out recent performance tests on the scalability of NGINX to load balance WebSocket connections.

The WebSocket protocol is different from the HTTP protocol, but the WebSocket handshake is compatible with HTTP, using the HTTP Upgrade facility to upgrade the connection from HTTP to WebSocket. This allows WebSocket applications to more easily fit into existing infrastructures. For example, WebSocket applications can use the standard HTTP ports 80 and 443, thus allowing the use of existing firewall rules.

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.

NGINX Websocket Example

Here is a live example to show NGINX working as a WebSocket proxy. This example uses ws, a WebSocket implementation built on Node.js. NGINX acts as a reverse proxy for a simple WebSocket application utilizing ws and Node.js. These instructions have been tested with Ubuntu 13.10 and CentOS 6.5 but might need to be adjusted for other OSs and versions. For this example, the WebSocket server’s IP address is 192.168.100.10 and the NGINX server’s IP address is 192.168.100.20.

  1. If you don’t already have Node.js and npm installed, run the following command:

    • For Debian and Ubuntu:

      $ sudo apt-get install nodejs npm
    • For RHEL and CentOS:

      $ sudo yum install nodejs npm
  2. Node.js is installed as nodejs on Ubuntu and as node on CentOS. The example uses node, so on Ubuntu we need to create a symbolic link from nodejs to node:

    $ ln -s /usr/bin/nodejs /usr/local/bin/node
  3. To install ws, run the following command:

    $ sudo npm install ws

    Note: If you get the error message: “Error: failed to fetch from registry: ws”, run the following command to fix the problem:

    $ sudo npm config set registry http://registry.npmjs.org/

    Then run the sudo npm install ws command again.

  4. ws comes with the program /root/node_modules/ws/bin/wscat that we will use for our client, but we need to create a program to act as the server. Create a file called server.js with these contents:

    console.log("Server started");
    var Msg = '';
    var WebSocketServer = require('ws').Server
    , wss = new WebSocketServer({port: 8010});
    wss.on('connection', function(ws) {
    ws.on('message', function(message) {
    console.log('Received from client: %s', message);
    ws.send('Server received from client: ' + message);
    });
    });
  5. To execute the server program, run the following command:
    $ node server.js
  6. The server prints an initial "Server started" message and then listens on port 8010, waiting for a client to connect to it. When it receives a client request, it echoes it and sends a message back to the client containing the message it received. To have NGINX proxy these requests, we create the following configuration:

    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;
    }
    }
    }

    NGINX listens on port 8020 and proxies requests to the backend WebSocket server. The proxy_set_header directives enable NGINX to properly handle the WebSocket protocol.

  7. To test the server, we run wscat as our client:

    $ /root/node_modules/ws/bin/wscat --connect ws://192.168.100.20:8020

    wscat connects to the WebSocket server through the NGINX proxy. When you type a message for wscat to send to the server, you see it echoed on the server and then a message from the server appears on the client. Here’s a sample interaction:

    Server: Client:
    $ node server.js 
    Server started
     
     
     
     
     
    wscat --connect ws://192.168.100.20:8020
    Connected (press CTRL+C to quit)
    > Hello
    Received from client: Hello  
      < Server received from client: Hello

    Here we see that the client and server are able to communicate
    through NGINX which is acting as a proxy and messages can continue to be
    sent back and forth until either the client or server disconnects. All
    that is needed to get NGINX to properly handle WebSocket is to set the
    headers correctly to handle the Upgrade request that upgrades the
    connection from HTTP to WebSocket.

Nginx反向代理websocket配置实例(官网)的更多相关文章

  1. Nginx反向代理websocket配置实例

    最近有一个需求,就是需要使用 nginx 反向代理 websocket,经过查找一番资料,目前已经测试通过,本文只做一个记录 复制代码 代码如下: 注: 看官方文档说 Nginx 在 1.3 以后的版 ...

  2. NGINX: 反向代理 websocket

    参考: [ Using multiple nodes ] [ Nginx 官网 WebSocket proxying ] 关于 websocket 的介绍可以看阮大大的这篇 [ WebSocket 教 ...

  3. Centos7 nginx 反向代理的配置

    一.正向代理与反向代理 1.正向代理 正向代理往VPN理解 正向代理,也就是传说中的代理,他的工作原理就像一个跳板(VPN),简单的说: 我是一个用户,我访问不了某网站,但是我能访问一个代理服务器,这 ...

  4. Nginx反向代理的配置

    Chapter: Nginx基本操作释疑 1. Nginx的端口修改问题 2. Nginx 301重定向的配置 3. Windows下配置Nginx使之支持PHP 4. Linux下配置Nginx使之 ...

  5. nginx反向代理的配置优化

    作者:守住每一天 blog:liuyu.blog.51cto.combbs:bbs.linuxtone.orgmsn:liuyubj520#hotmail.comemail:liuyu105#gmai ...

  6. 【netcore基础】CentOS 7.6.1810 搭建.net core 2.1 linux 运行环境 nginx反向代理 supervisor配置自启动

    之前写过一篇Ubuntu的环境搭建博客,感觉一些配置大同小异,这里重点记录下 nginx 作为静态 angular 项目文件服务器的配置 参考链接 [netcore基础]ubuntu 16.04 搭建 ...

  7. 配置Nginx反向代理WebSocket,以代理noVNC为例

    什么是Nginx Nginx (engine x) 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器. Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮 ...

  8. 配置 Nginx 反向代理 WebSocket

    用Nginx给网站做反向代理和负载均衡是广泛使用的一种Web服务器部署技术.不仅能够保证后端服务器的隐蔽性,还可以提高网站部署灵活性. 今天我们来讲一下,如何用Nginx给WebSocket服务器实现 ...

  9. [svc]tomcat目录结构/虚拟主机/nginx反向代理cache配置

    tomcat目录文件 /usr/local/tomcat/bin/catalina.sh stop sleep 3 /usr/local/tomcat/bin/catalina.sh start to ...

随机推荐

  1. 在虚拟机下安装Ubuntu

    目录: 1.安装虚拟机 2.在虚拟下安装Ubuntu 本文将按照目录分两步来讲一下在虚拟机下安装Ubuntu.第一步是安装虚拟机,第二步是在虚拟机下安装Ubuntu. 安装虚拟机 下载虚拟机链接以及激 ...

  2. Visual Studio win平台 AI环境搭建

    内容提要:我觉得难点主要出在下载上,程序跑的都挺流畅的.下载有时会失败. 1.下载安装git.这一步主要为了下载示例和自动安装环境的python代码,直接去github上用网页下载也是一样的,git不 ...

  3. 第38次Scrum会议(12/4)【欢迎来怼】

    一.小组信息 队名:欢迎来怼 小组成员 队长:田继平 成员:李圆圆,葛美义,王伟东,姜珊,邵朔,阚博文 小组照片 二.开会信息 时间:2017/12/4 17:50~18:20,总计30min. 地点 ...

  4. 团队冲刺——Five

    昨天: 司宇航:web项目如何部署到公网,把网址做成桌面图标链接,登录记住密码功能. 王金萱:注册和登录界面,用户数据库的信息录入. 马佳慧:做界面. 季方:处理爬虫数据,实现统计功能. 遇到的问题: ...

  5. cnblogs用户体验评价

    1. 是否提供良好的体验给用户(同时提供价值)? 博客园就相当于现在生活中处处可见的微博,所有人都在上面发表自己的一些看法,当然我们比较关注的是计算机编程方面的一些博客,大多数编程人员愿意分享自己的代 ...

  6. OSG学习:计算纹理坐标

    在很多时候,直接指定纹理坐标是非常不方便的,如曲面纹理坐标,只有少数的曲面(如圆锥.圆柱等)可以在不产生扭曲的情况下映射到平面上,其他的曲面在映射到表面时都会产生一定程度的扭曲.一般而言,曲面表面的曲 ...

  7. Scrum Meeting Beta - 8

    Scrum Meeting Beta - 8 NewTeam 2017/12/7 地点:新主楼F座二楼 任务反馈 团队成员 完成任务 计划任务 安万贺 完成了博文详情的存储Issue #150Pull ...

  8. git使用教程推荐

    Git使用教程 一:Git是什么? Git是目前世界上最先进的分布式版本控制系统. 二:SVN与Git的最主要的区别? SVN是集中式版本控制系统,版本库是集中放在中央服务器的,而干活的时候,用的都是 ...

  9. 总结MySQL修改最大连接数的两个方式

    最大连接数是可以通过mysql进行修改的,mysql数据库修改最大连接数常用有两种方法,今天我们分析一下这两种方法之间的特点和区别,以便我们能更好的去维护mysql.下面我们来看一下mysql修改最大 ...

  10. vSphere Client 连接ESXi 或者是vCenter 时虚拟机提示VMRC异常的解决办法

    1. 自己的vSphere 连接vCenter 向管理虚拟机 结果发现总是有异常. 提示如图示 VMRC控制台的连接已经断开 2. 花了比较长的时间也没搞定. 后来百度发现 关闭一个进程 然后重新登录 ...