负载均衡——Nginx

目的

简单感受下Nginx的负载均衡。

环境准备

既然是负载均衡,那机器肯定要多台。为了方便,我们就用两台机器就好了,其中一台作为反向代理和后端服务器,另一台作为后端服务器。不嫌麻烦的话,最好反向代理和后端服务器分开,性能和可用性都会提高。

机器作用
192.168.0.100反向代理和后端web服务器
192.168.0.200后端web服务器

操作

1、在两台机器上分别安装nginx。

yum install -y ngnix

2、192.168.0.100上配置反向代理,后端机器为自身和.200机器。新增如下配置文件,

[root@192_168_0_100 ~]# cat /etc/nginx/conf.d/reverse.conf
upstream myserver {
    server 192.168.0.100:80 weight=10;
    server 192.168.0.200:80 weight=20;
}
server {
    server_name localhost;
    listen 8080;
    location / {
        proxy_pass http://myserver/;
    }
}

这里均衡策略选择按权重来,也就是1:2的关系。因为.100机器本身也作为web服务器,因此,在配置反向代理时就要设置除80端口外的port作为反向代理端口。

3、为了区分两台后端web服务器,我们修改下两台web服务器的index.html内容。

[root@192_168_0_100 ~]# cat /usr/share/nginx/html/index.html
This is 192.168.0.100

[root@192_168_0_200 ~]# cat /usr/share/nginx/html/index.html
This is 192.168.0.200

4、启动两台web服务器的nginx服务,

service start nginx

在.100服务器上可以看到nginx在监听80和8080两个端口,

[root@192_168_0_100 ~]# netstat -antp | grep nginx
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      75412/nginx         
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      75412/nginx         
tcp        0      0 :::80                       :::*                        LISTEN      75412/nginx 

而.200只监听80端口,

[root@192_168_0_200 /]# netstat -antp | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      106411/nginx: maste 
tcp6       0      0 :::80                   :::*                    LISTEN      106411/nginx: maste 

5、我们通过curl命令测试下负载均衡的效果,因为是2:1的权重,因此我们测试6次,找另一台机器.250测试,当然在.100和.200上测试也是可以的。

[root@192_168_0_250 /home]# curl -x http://192.168.0.100:8080 http://192.168.0.100/
This is 192.168.0.200
[root@192_168_0_250 /home]# curl -x http://192.168.0.100:8080 http://192.168.0.100/
This is 192.168.0.100
[root@192_168_0_250 /home]# curl -x http://192.168.0.100:8080 http://192.168.0.100/
This is 192.168.0.200
[root@192_168_0_250 /home]# curl -x http://192.168.0.100:8080 http://192.168.0.100/
This is 192.168.0.200
[root@192_168_0_250 /home]# curl -x http://192.168.0.100:8080 http://192.168.0.100/
This is 192.168.0.100
[root@192_168_0_250 /home]# curl -x http://192.168.0.100:8080 http://192.168.0.100/
This is 192.168.0.200

可见,测试结果和我们设置的均衡策略是一致的。

当然,nginx还提供其他均衡策略,比如,轮训(默认),ip_hash(根据ip分配),least_conn(最少连接)等,这里就不一一测试了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值