Nginx 负债均衡的几种方式

Nginx 负载均衡 About 2,056 words

轮询

http {
    upstream loadbalanceone{
        server 127.0.0.1:9000;
        server 127.0.0.1:10000;
    }
    server {
        listen 8000;
        location / {
            proxy_pass http://loadbalanceone/;
        }
    }
}

权重

http {
    upstream loadbalancetwo{
        server 127.0.0.1:9000 weight=1;
        server 127.0.0.1:10000 weight=2;
    }
    server {
        listen 8000;
        location / {
            proxy_pass http://loadbalancetwo/;
        }
    }
}

ip_hash

根据IP的哈希值来转发。

ip_hash可以和weight共用,当hash冲突时可以在几台机器间按权重再分配。

ip_hash不支持backup指令。

http {
    upstream loadbalancethree{
        ip_hash;
        server 127.0.0.1:9000 weight=1;
        server 127.0.0.1:10000 weight=2;
    }
    server {
        listen 8000;
        location / {
            proxy_pass http://loadbalancethree/;
        }
    }
}

least_conn

根据连接数来转发,转发至最少连接的那台服务器。

http {
    upstream loadbalancefour{
        least_conn;
        server 127.0.0.1:9000 weight=1;
        server 127.0.0.1:10000 weight=2;
    }
    server {
        listen 8000;
        location / {
            proxy_pass http://loadbalancefour/;
        }
    }
}

url_hash

http {
    upstream loadbalancefive{
        hash $request_uri;
        server 127.0.0.1:9000 weight=1;
        server 127.0.0.1:10000 weight=2;
    }
    server {
        listen 8000;
        location / {
            proxy_pass http://loadbalancefive/;
        }
    }
}

其他相关

downbackupmax_failsfail_timeout等指令。

  • down:表示当前服务不参与负载均衡。
  • backup:表示其他非backup服务都down或繁忙时,请求该服务,这个服务压力最小。
  • max_fails:允许请求失败的最大次数,默认为1,当超过max_fails将不再调度到该服务。
  • fail_timeout:超过max_fails后,暂停调度到该服务的时间。
http {
    upstream loadbalancesix{
        server 127.0.0.1:9000 down;
        server 127.0.0.1:10000 backup;
        server 127.0.0.1:11000 max_fails=1 fail_timeout=60s;
    }
    server {
        listen 8000;

        location / {
            proxy_pass http://loadbalancesix/;
            proxy_connect_timeout 3s;
        }
    }
}

注意

ip_hash不支持backup指令。

nginx: [emerg] balancing method does not support parameter "backup" in ./conf/nginx.conf:61
Views: 2,845 · Posted: 2021-05-12

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh