萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Nginx URL 雜湊負載均衡配置與原始碼編譯安裝全紀錄

記錄 Nginx 0.7.58 套用 upstream_hash 模組實現 URL 雜湊分發的完整編譯安裝與配置流程,適用於需會話親和性的叢集場景。

軟體版本與下載

  • pcre-8.02.tar.gz
  • nginx-0.7.58.tar.gz
  • Nginx_upstream_hash-0.3.1.tar.gz (第三方模組)

編譯安裝步驟

  1. 安裝 PCRE
    tar -zxvf pcre-8.02.tar.gz
    cd pcre-8.02
    ./configure && make && make install
  2. 套用 upstream_hash 修補程式
    tar -zxvf nginx-0.7.58.tar.gz
    tar -zxvf Nginx_upstream_hash-0.3.1.tar.gz
    cd nginx-0.7.58
    patch -p0 < ../nginx_upstream_hash-0.3.1/nginx.patch
  3. 配置並編譯 Nginx
    groupadd www
    useradd -g www www
    
    ./configure \
      --prefix=/usr/local/webserver/nginx \
      --user=www --group=www \
      --add-module=../nginx_upstream_hash-0.3.1 \
      --with-http_ssl_module \
      --with-http_stub_status_module
    
    make && make install
  4. 驗證配置檔語法
    /usr/local/webserver/nginx/sbin/nginx -t
  5. 啟動服務
    /usr/local/webserver/nginx/sbin/nginx

URL Hash 負載均衡配置範例

# /usr/local/webserver/nginx/conf/nginx.conf
user www www;
worker_processes 10;
error_log logs/error.log;
worker_rlimit_nofile 51200;

events {
    use epoll;
    worker_connections 51200;
}

http {
    include mime.types;
    default_type application/octet-stream;
    keepalive_timeout 120;
    tcp_nodelay on;

    upstream backend_cluster {
        server 192.168.1.10:8080;
        server 192.168.1.11:8080;
        hash $request_uri;   # 核心:依請求 URI 雜湊分發
    }

    server {
        listen 80;
        server_name your.domain.com;

        location / {
            proxy_pass https://backend_cluster;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        location /nginx_status {
            stub_status on;
            access_log off;
        }
    }
}

管理腳本

#!/bin/sh
# /usr/local/webserver/nginx/nginx.sh
CWD=$(pwd)
case $1 in
    start)
        /usr/local/webserver/nginx/sbin/nginx
        ;;
    stop)
        kill -2 $(ps -ef | grep "nginx/sbin/nginx" | grep -v grep | awk '{print $2}')
        ;;
    restart)
        cd "$CWD"
        $0 stop
        sleep 1
        $0 start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
esac
exit 0
chmod +x nginx.sh
./nginx.sh start|stop|restart

關鍵點總結

  • hash $request_uri 確保同一 URL 落在同一後端,維持 Session 一致性
  • 後端 Tomcat 需配置 jvmRoute 配合 Session 複製或共享儲存 (Redis/Memcached)
  • 現代 Nginx (1.7+) 內建 ngx_http_upstream_consistent_hash,無需第三方補丁
copyright © 萬盛學電腦網 all rights reserved