首发于 Nginx
【Nginx】面试官问我Nginx能不能配置WebSocket?我给他现场演示了一番!!

【Nginx】面试官问我Nginx能不能配置WebSocket?我给他现场演示了一番!!

写在前面

当今互联网领域,不管是APP还是H5,不管是微信端还是小程序,只要是一款像样点的产品,为了增加用户的交互感和用户粘度,多多少少都会涉及到聊天功能。而对于Web端与H5来说,实现聊天最简单的就是使用WebSocket了。而在实现WebSocket聊天的过程中,后台也往往会部署多个WebSocket服务,多个WebSocket服务之间,可以通过Nginx进行负载均衡。今天,我们就来一起说说Nginx是如何配置WebSocket的。

Nginx配置WebSocket

Nginx配置WebSocket也比较简单,只需要在nginx.conf文件中进行相应的配置。这种方式很简单,但是很有效,能够横向扩展WebSocket服务端的服务能力。

先直接展示配置文件,如下所示(使用的话直接复制,然后改改ip和port即可)

map $http_upgrade $connection_upgrade { 
    default upgrade; 
    '' close; 
upstream wsbackend{ 
    server ip1:port1; 
    server ip2:port2; 
    keepalive 1000; 
server { 
    listen 20038; 
    location /{ 
        proxy_http_version 1.1; 
        proxy_pass http://wsbackend; 
        proxy_redirect off; 
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_read_timeout 3600s; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
        proxy_set_header Upgrade $http_upgrade; 
        proxy_set_header Connection $connection_upgrade; 
}

接下来,我们就分别分析上述配置的具体含义。

首先:

map $http_upgrade $connection_upgrade { 
    default upgrade; 
    '' close; 
}

表示的是:

  • 如果 $http_upgrade 不为 '' (空),则 $connection_upgrade 为 upgrade 。
  • 如果 $http_upgrade 为 '' (空),则 $connection_upgrade 为 close。

其次:

upstream wsbackend{ 
    server ip1:port1; 
    server ip2:port2; 
    keepalive 1000; 
}

表示的是 nginx负载均衡: 两台服务器 (ip1:port1)和(ip2:port2) 。

keepalive 1000 表示的是每个nginx进程中上游服务器保持的空闲连接,当空闲连接过多时,会关闭最少使用的空闲连接.当然,这不是限制连接总数的,可以想象成空闲连接池的大小,设置的值应该是上游服务器能够承受的。

最后:

server { 
    listen 20038; 
    location /{ 
        proxy_http_version 1.1; 
        proxy_pass http://wsbackend; 
        proxy_redirect off;
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr;