Nginx ip_hash 不会对流星后端的连接进行负载平衡

Nginx ip_hash 不会对流星后端的连接进行负载平衡

启用 ip_hash 后,我无法让 nginx 对内部连接进行负载平衡。我需要粘性会话,因为我在后端使用带套接字的 Meteor,但所有请求始终到达同一个后端。

nginx 访问日志文件显示以下 IP 地址:

192.168.0.20 - - [xx/xxx/2017:xx:xx:xx +xxxx] "GET /favicon.ico HTTP/1.1"  404 5 "http://xxxx.lokal/" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
192.168.0.11 - - [xx/xxx/2017:xx:xx:xx +xxxx] "GET /sockjs/602/dpkl6lfe/websocket HTTP/1.1" 101 55045 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
192.168.0.208 - - [xx/xxx/2017:xx:xx:xx +xxxx] "GET /sockjs/031/cx1kml79/websocket HTTP/1.1" 101 1146677 "-" "Mozilla/5.0 (iPad; CPU OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Version/10.0 Mobile/14D27 Safari/602.1"

是不是因为它们都来自同一个 192.168.0.* 子网?如果是这样,我该如何改变这种行为?

这是我的配置文件:

user  www;
worker_processes  4;
error_log  /var/log/nginx/error.log;

events {
 worker_connections  1024;
}

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

    upstream demo {
      ip_hash;
      server 127.0.0.1:5000;
      server 127.0.0.1:5001;
    }

    include       mime.types;
    default_type  application/octet-stream;
    access_log  /var/log/nginx/access.log;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    gzip on;
    gzip_disable "msie6";

    server_tokens off; # for security-by-obscurity: stop displaying nginx version

     server {
          listen       80;
              server_name xxxx.lokal;

          location / {
            proxy_pass http://demo;
            proxy_redirect      off;
            proxy_set_header    Host              $host;
            proxy_set_header    X-Real-IP         $remote_addr;
            proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header    X-Forwarded-Proto $scheme;
            proxy_http_version 1.1;
            proxy_set_header    Upgrade           $http_upgrade; # allow websockets
            proxy_set_header    Connection        "upgrade"; 
            proxy_buffering     off;
            proxy_connect_timeout 43200000;
            proxy_read_timeout    43200000;
            proxy_send_timeout    43200000;

            if ($uri != '/') {
                expires 30d;
            }
    }
}

答案1

是的,发生这种情况是因为ip_hash仅使用 IP 地址的前三个八位字节来选择后端节点。

您可以使用hash $remote_addr;指令让 nginx 使用完整的远程 IP 地址进行哈希处理。这样做的缺点是,如果某个节点发生故障,则所有哈希映射都会更改,并且会话将丢失。

有关上游选择方法的更多信息,请访问 nginx 上游模块文档

相关内容