nginx负载均衡策略

发布时间 2024-01-03 22:40:45作者: 曹伟666

nginx负载均衡配置:

    upstream myservers {
        server  localhost:8081;
        server  localhost:8082;
    }
    server {
        listen       8080;
        server_name  localhost;
        location / {
            proxy_pass  http://myservers;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

负载均衡策略:

1、轮询:

          参数:

fail_timeout与max_fails结合使用。
max_fails 设置在fail_timeout参数设置的时间内最大失败次数,如果在这个时间内,所有针对该服务器的请求都失败了,那么认为该服务器会被认为是停机了
fail_time 服务器会被认为停机的时间长度,默认为10s。
backup 标记该服务器为备用服务器。当主服务器停止时,请求会被发送到它这里。
down 标记服务器永久停机了。

 

例如:

upstream myservers {
        server  localhost:8081 max_fails=3 fail_timeout=20s fail_time=100s;  #20秒内有3次请求失败则认为服务器挂机,停止访问100秒
        
     server localhost:
8082;
      server  localhost:8082 backup #表示该服务器为备用服务器
}

2、权重:

upstream myservers {
        server  localhost:8081; max_fails=3 fail_timeout=20s fail_time=100s;  #20秒内有3次请求失败则认为服务器挂机,停止访问100秒
     server  localhost:8082 weight=2; #默认权重为1,2代表访问该服务器的几率是其他服务器的2倍
      server  localhost:8082; backup #表示该服务器为备用服务器
}

3、ip_hash:

upstream myservers {
     ip_hash; #表示同一个ip固定访问桶一台服务器 server localhost:
8081; max_fails=3 fail_timeout=20s fail_time=100s; #20秒内有3次请求失败则认为服务器挂机,停止访问100秒      server localhost:8082 weight=2; #默认权重为1,2代表访问该服务器的几率是其他服务器的2倍      server localhost:8082; backup #表示该服务器为备用服务器 }

4、least_conn:

upstream myservers {
      least_conn; #表示把请求分配给当前访问线程最少的服务器
        server  localhost:8081; max_fails=3 fail_timeout=20s fail_time=100s;  #20秒内有3次请求失败则认为服务器挂机,停止访问100秒
     server  localhost:8082 weight=2; #默认权重为1,2代表访问该服务器的几率是其他服务器的2倍
      server  localhost:8082; backup #表示该服务器为备用服务器
}