nginx學習九 upstream 負載均衡

  • 語法
    Syntax: upstream name {...}
    Default:--
    Context:http

     

  • 後端服務器在負載均衡調度中的狀態:
    down 當前的server暫時不參與負載均衡
    backup 預留的備份服務器
    max_fails 容許請求失敗的次數
    fail_timeout 通過max_fails失敗後,服務暫停的時間
    max_conns 限制最大的接收的鏈接數

     

  •  nginx 的調度算法:
    輪詢  按時間順序逐一分配到不一樣的後端服務器
    加權輪詢   weight值越大,分配到的訪問概率越高
    ip_hash 每一個請求按訪問IP的hash結果分配,這樣來自同一個IP的請求,固定訪問一個
    least_conn 最少鏈接數,哪一個機器鏈接數少就分發
    url_hash 按照訪問的URL的hash結果來分配請求,是每一個URL定向到同一個後端服務器
    hash關鍵數值 hash自定義的key

     

  • 例 /etc/nginx/conf.d/default.con
    server {
        listen       8001;
        server_name  localhost;
    
        #charset koi8-r;
        access_log  /var/log/nginx/server.access.log  main;
    
        location / {
            root   /opt/app/code1;
            index  index.html index.htm;
        }
    ... ...
    }
    
    server {
        listen       8002;
        server_name  localhost;
    
        #charset koi8-r;
        access_log  /var/log/nginx/server.access.log  main;
    
        location / {
            root   /opt/app/code2;
            index  index.html index.htm;
        }
    ... ...
    }
    
    server {
        listen       8003;
        server_name  localhost;
    
        #charset koi8-r;
        access_log  /var/log/nginx/server.access.log  main;
    
        location / {
            root   /opt/app/code3;
            index  index.html index.htm;
        }
    ... ...
    }
    
    
    server {
        listen       80;
        server_name  localhost;
    
        #charset koi8-r;
        access_log  /var/log/nginx/test_proxy.access.log  main;
    
        location / {
            proxy_pass http://test_upstream;
        }
    ... ...
    }
    
    
    ##普通輪詢
    upstream test_upstream {
    	server localhost:8001;
    	server localhost:8002;
    	server localhost:8003;
    }

     

  • 加權輪詢
    upstream test_upstream {
        server localhost:8001;
        server localhost:8002 weight=5;
        server localhost:8003;
    }

     

  • 備份節點 
    upstream test_upstream {
        server localhost:8001 down; 
        server localhost:8002 backup;
        server localhost:8003 max_fails=1 fail_timeout=10s;
    }

     

  • ip_hash 
    upstream test_upstream {
    	ip_hash;
    	server localhost:8001; 
    	server localhost:8002;
    	server localhost:8003;
    }

     

  • url_hash  語法(1.7.2版本開始)
    Syntax: hash key [consistent];
    Default: --
    Context: upstream
    ##例:
    upstream test_upstream {
    	hash $request_uri;
    	server localhost:8001; 
    	server localhost:8002;
    	server localhost:8003;
    }
     
相關文章
相關標籤/搜索