Skip to content


nginx系列(4):实现负载均衡(ngx_http_upstream)

在web应用中,当网站的访问量大的时候很自然的就会想到用多台web服务器集群去分担单台访问的压力,对于小的网站,自然没有大量的现金去买优秀的负载均衡的硬件设备.那么nginx做代理前端实现负载均衡的目的会是一个很好的选择。
简单的例子:

upstream load_balance {
server localhost:8088 ;
server 192.168.1.4:8080 down;
server home.ucenter weight=2;
server backserver:9100 backup;

}
server {
listen 80;
#location / {
# proxy_pass http://home.ucenter/;
#}
location / {
proxy_pass http://load_balance;
}
server_name proxy;
}

配置解释:
1)定义一个server集群load_balance,可以用域名,也可以直接用IP,(要注意不要加上http://).
2)用前一节讲的proxy_pass实现代理。把域名代理到集群名上面.

3)结束了,哈哈。简单吧。
单台server的设置:
1.down 表示单前的server暂时不参与负载
2.weight 默认为1.weight越大,负载的权重就越大。
3.max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误
4.fail_timeout:max_fails次失败后,暂停的时间。
5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力正常最小。
附上英文:
# weight = NUMBER – set weight of the server, if not set weight is equal to one.

#max_fails = NUMBER – number of unsuccessful attempts at communicating with the server within the time period (assigned by parameter fail_timeout) after which it is considered inoperative. If not set, the number of attempts is one. A value of 0 turns off this check. What is considered a failure is defined by proxy_next_upstream or fastcgi_next_upstream (except http_404 errors which do not count towards max_fails).

#fail_timeout = TIME – the time during which must occur *max_fails* number of unsuccessful attempts at communication with the server that would cause the server to be considered inoperative, and also the time for which the server will be considered inoperative (before another attempt is made). If not set the time is 10 seconds. fail_timeout has nothing to do with upstream response time, use proxy_connect_timeout and proxy_read_timeout for controlling this.

# down – marks server as permanently offline, to be used with the directive ip_hash.

# backup – (0.6.7 or later) only uses this server if the non-backup servers are all down or busy

Posted in linux, nginx, 技术.

Tagged with , , .


One Response

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Continuing the Discussion

  1. 臭皮匠 » Blog Archive » 关于web系统扩展的几点记录 linked to this post on 2008年11月1日

    [...] 2)第四层与第7层负载平衡注意这个第字。刚接触的时候不理解,直接看成四层,与7层。呵呵,7层比4层多三层当然7层要牛很多。第7层的确比第4层更灵活,但原因绝对不是7比4大.第4层与第7层指的是网络分层.传统的负载平衡是在第四层处理的,用户的请求来源与目标IP地址与端口在这一层被捕获,有了这些信息就可以把这个连接引导到后台正常的端口上。最简单的第四层负载采用的是循环算法(round robin)。就是把请请求循环发送到生产服务器上。除了循环之外,也可以做随机算法。在两种方法中都可以加上权重,对权重比较高的生产服务器,只要有队列中重复出现几次那么被分配到流量的比重就越高。第7层负载比第4层负载出现的晚,它比第4层更加易活。因为第7层负载平衡器检测HTTP请求,这能够查看请求和请求的标头,并将这些信息纳入平衡策略的考虑中。这样就可以做基于URL平衡,可以确保对特定资源的所有请求都被调度到同一台机器上,这样的方便在同一台机器上做缓存,提高缓存命中率。这就是比第四层优秀的原因之一.听说apache的mod_rewrite模块加上一些脚本就可以做第7层的负载,具体我没有实施过,不过试过用ngnix做过第4层负载平衡,十分简单:) [...]



Some HTML is OK

or, reply to this post via trackback.