nginx负载均衡

来源:互联网 发布:淘宝代付一天多少次 编辑:程序博客网 时间:2024/06/14 05:22

nginx负载均衡

介绍

跨多个应用程序实例的负载平衡是一种常用的优化资源利用、最大化吞吐量、减少延迟和确保容错配置的技术。
它可以使用Nginx作为非常有效的HTTP负载均衡的流量分配的几个应用服务器,以提高性能,可扩展性和可靠性与Nginx Web应用程序。

负载均衡方法

  • round-robin — requests to the application servers are distributed in a round-robin fashion,
  • least-connected — next request is assigned to the server with the least number of active connections,
  • ip-hash — a hash-function is used to determine what server should be selected for the next request (based on the client’s IP address).

1. round-robin (轮询)

如果负载均衡方法不是特殊的配置,那么负载均衡策略默认的是round-robin。
一个最简单的round-robin配置如下:

http {    upstream myapp1 {        server srv1.example.com;        server srv2.example.com;        server srv3.example.com;    }    server {        listen 80;        location / {            proxy_pass http://myapp1;        }    }}

示例:
修改nginx的配置文件,增加以下配置
命令:vim /usr/local/nginx/conf/nginx.conf

upstream proxy_first {    server 192.168.44.129:8080;    server 192.168.44.129:8081;}server {    listen 80;    server_name www.tyrone.com;    location / {        index proxy_first.html;        root /opt/static/proxy;        proxy_pass http://proxy_first;    }}

重启nginx./../sbin/nginx -s reload

在浏览器中输入http://www.tyrone.com,第一次将访问代理将请求转发至port=8080web服务器上。如图:
这里写图片描述
再次刷新后,代理会将请求转发至port=8081的web服务器上。如图:
这里写图片描述
这时候,通过nginx实现了最基本的负载均衡策略。
轮询策略是通过各个服务器轮流替换实现负载均衡的。

注意:实现上述需求需要

  • 准备n台内部web服务器,并将其首页面做标识用以区分。本例中采用了两台tomcat服务器
  • http://www.tyrone.com域名做一下host。

Weighted load balancing(权重轮询策略)

upstream proxy_first {    server 192.168.44.129:8080;    server 192.168.44.129:8081;}

假如port=8080的这台web服务器的性能要优于port=8081这台web服务器,那么使用轮询策略将会加重8081这台服务器的压力。这个时个就需要采用权重轮询策略。
配置如下:

upstream myapp1 {    server srv1.example.com weight=3;    server srv2.example.com;    server srv3.example.com;}

这里使用weight实现权重轮询策略。上述配置表明,每5个请求到来时,会有三个请求指向srv1.example.com,另外两个请求分别指向srv2.example.com和srv3.example.com;

参考链接:
http://nginx.org/en/docs/http/load_balancing.html