nginx下websocket反向代理初体验

  |   0 评论   |   0 浏览

背景

初体验

反向代理配置

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;
            proxy_set_header Host $host;
        }
    }
}

日志记录配置

log_format timed_combined '$remote_addr - $remote_user [$time_local] '
                              '"$request" $status $body_bytes_sent '
                              '"$http_referer" "$http_user_agent" '
                              '"$request_time" "$upstream_connect_time" "$upstream_header_time" "$upstream_response_time"';

    access_log  /var/log/nginx/websocket.log timed_combined ;

其中:

变量名称含义中文含义
request_timeFull request time, starting when NGINX reads the first byte from the client and ending when NGINX sends the last byte of the response body从请求到建立连接到发送完最后一个内容字节的时间(秒)
upstream_connect_timeTime spent establishing a connection with an upstream server建立连接的时间(秒)
upstream_header_timeTime between establishing a connection to an upstream server and receiving the first byte of the response header从建立连接到发送第一个响应头字节的时间(秒)
upstream_response_timeTime between establishing a connection to an upstream server and receiving the last byte of the response body从建立连接到发送完最后一个内容字节的时间(秒)

nginx时间变量关系图

keep alive长连接

[3]

Syntax:    keepalive connections;

The connections parameter sets the maximum number of idle keepalive connections to upstream servers that are preserved in the cache of each worker process. When this number is exceeded, the least recently used connections are closed.

It should be particularly noted that the keepalive directive does not limit the total number of connections to upstream servers that an nginx worker process can open. The connections parameter should be set to a number small enough to let upstream servers process new incoming connections as well.

client和nginx之间是短连接,nginx和upstream之间也是可以开启长连接的。

http {
    server {
        location /  {
            proxy_http_version 1.1;                    // 这两个最好也设置
            proxy_set_header Connection "";
        }
    }
}

参考

  1. NGINX as a WebSocket Proxy
  2. [Linux] nginx记录多种响应时间
  3. 支持keep alive长连接