Nginx

Nginx ip_hash 不對流星後端的連接進行負載平衡

  • November 6, 2019

我無法讓 nginx 在啟用 ip_hash 的情況下對內部連接進行負載平衡。我需要粘性會話,因為我在帶有套接字的後端使用流星,但所有請求總是命中同一個後端。

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

是的,這是因為ip_hash只使用 IP 地址的前三個八位字節來選擇後端節點。

您可以使用hash $remote_addr;指令使 nginx 使用完整的遠端 IP 地址進行雜湊。不利的一面是,如果一個節點出現故障,所有雜湊映射都會更改,並且會話將失去。

更多關於上游選擇方法的資訊可以在 nginx 上游模組文件中找到。

引用自:https://serverfault.com/questions/839148