zhangpengfei00 发表于 2018-11-11 11:27:36

LB集群之nginx-M四月天

  上篇文章讲了LVS的负载均衡:http://msiyuetian.blog.51cto.com/8637744/1700710
  这篇文章讲nginx的负载均衡,它实际上和nginx的代理是同一个功能,只是把之前代理一台机器改为代理多台机器而已。nginx 的负载均衡和LVS相比,nginx属于更高级的应用层,不牵扯到 IP 和内核的改动,它只是单纯地把用户的请求转发到后面的机器上。这就意味着,后端的rs不需要配置公网 IP。
  一、nginx代理实现集群
  1、准备工作
  准备三台机器
  nginx 分发器(一个公网 ip192.168.1.109 和一个内网 ip192.168.0.109)。
  rs1 只有内网 ip(192.168.0.112)
  rs2 只有内网 ip(192.168.0.113)
  同时,三台机器都要安装nginx,并开启。
  # yum install -y nginx   //若没有,可先安装epel扩展源:epel-release
  # /etc/init.d/nginx start
  2、配置
  在 nginx 分发器上编辑配置文件
  # vim /usr/local/nginx/conf/vhosts/lb.conf   //加入如下内容
  upstream test {
  ip_hash;
  server 192.168.0.112;
  server 192.168.0.113;
  }
  server {
  listen 80;
  server_name www.tpp.com;
  location / {
  proxy_pass http://test/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  }
  重启nginx
  # /etc/init.d/nginx restart
  在rs1和rs2上配置
  我们修改下nginx的默认页面
  rs1上
  echo "rs1 nginx" > /usr/share/nginx/html/index.html
  rs2上
  echo "rs2 nginx" > /usr/share/nginx/html/index.html
  3、测试
  首先rs1和rs2都要关闭防火墙
  # iptables -F
  然后在nginx分发器上执行测试命令
  # curl -xlocalhost:80 www.tpp.com
  rs1 nginx
  # curl -xlocalhost:80 www.tpp.com
  rs2 nginx
  # curl -xlocalhost:80 www.tpp.com
  rs1 nginx
  # curl -xlocalhost:80 www.tpp.com
  rs2 nginx
  # curl -xlocalhost:80 www.tpp.com
  rs1 nginx
  # curl -xlocalhost:80 www.tpp.com
  rs2 nginx
  二、根据访问的目录来区分后端的web
  需求:当请求的目录是 /aaa/ 则把请求发送到机器rs1,除了目录/aaa/外,其他的请求发送到机器rs2.
  在分发器上配置
  upstream testa {
  server 192.168.0.112;
  }
  upstream testb {
  server 192.168.0.113;
  }
  server {
  listen 80;
  server_name www.tpp.com;
  location /aaa/{
  proxy_pass http://testa/aaa/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  location /{
  proxy_pass http://testb/;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  }
  注意:
  1)以上配置文件中的 test、testa 以及 testb 都是自定义的,随便写。
  2)proxy_pass http://testa/aaa/这里必须要加这个目录,不然就访问到根目录了。
  3)根据访问的目录来区分后端的web,这个LVS是做不到的。

页: [1]
查看完整版本: LB集群之nginx-M四月天