nginx负载均衡

在nginx中,当反向代理的后端有多台服务器,自然就形成了负载均衡。但是反向代理的配置proxy_pass只能配置一台服务器,如果配置多台服务器,nginx启动会报错。这个时候就需要通过upstream指令,将多台服务器绑定在一个组内,再将组名传给proxy_pass即可实现负载均衡。

注:默认的均衡算法很简单,就是针对后端服务器的顺序,逐个请求,也有其他负载均衡算法,如一致哈希,需要安装第三方模块。

第三方模块一致性哈希:https://www.nginx.com/resources/wiki/modules/consistent_hash/

下载地址:https://github.com/replay/ngx_http_consistent_hash/archive/master.zip

 

负载均衡后端服务器状态

down:当前的server暂时不参与负载均衡。

backup:预留的备份服务器。

max_fails:允许请求失败的次数。

fail_timeout:经过max_fails失败后,服务器暂停的时间。

max_conns:限制最大的接收连接数。

例:

resolver 10.0.0.1;

upstream dynamic {
    zone upstream_dynamic 64k;

    server backend1.example.com      weight=5;
    server backend2.example.com:8080 fail_timeout=5s slow_start=30s;
    server 192.0.2.1                 max_fails=3;
    server backend3.example.com      resolve;
    server backend4.example.com      service=http resolve;

    server backup1.example.com:8080  backup;
    server backup2.example.com:8080  backup;
}

server {
    location / {
        proxy_pass http://dynamic;
        health_check;
    }
}

官方文档:

http://nginx.org/en/docs/http/ngx_http_upstream_module.html

 

注:nginx中使用了反向代理或负载均衡之后,用户请求后端的时候,在后端中产生的IP地址,是nginx服务器的地址,而不是用户的IP地址,这个时候就需要通过将remote_addr作为变量传给后端服务器。具体配置如下:

location ~* \.php$ {
    proxy_set_header X-Forworded-For $remote_addr;
    proxy_pass http://192.68.1.1:8080;
}

 

posted @ 2019-04-04 09:25  *年少轻狂*  阅读(122)  评论(0编辑  收藏  举报