说明
负载均衡分4层和7层,一般认为,nginx在7层转发,而lvs,haproxy作为4层的负载均衡。nginx转发效率高,且能够对业务处理控制力度更强,目前使用率很高。
本案例中,我们采用nginx的反向代理做负载均衡。
环境配置
| IP | 角色 | 说明 | 备注 |
| 192.168.10.105 | 调度器 | ||
| 192.168.10.106 | 工作机1 | ||
| 192.168.10.107 | 工作机1 | ||
| 192.168.10.108 | 工作机2 |
安装
使用ansible进行nginx的安装,ansible 安装及使用见博主文档 ansible的安装及使用。
配置集群信息
cat <<EOF >>/etc/ansible/hosts
[upstream]
192.168.10.[105:108]
EOF
安装相关工具。
ansible upstream -m shell -a " yum install epel-release -y "
ansible upstream -m shell -a " yum install nginx -y "
ansible upstream -m shell -a " systemctl enable nginx && systemctl start nginx "
ansible upstream -m shell -a " systemctl stop firewalld && setenforce 0 "
更改默认的html文件内容以便测试
[root@node ~]# ansible upstream -m shell -a "ip a |grep -oE '([0-9]+\.)+[0-9]+/[0-9]+' |grep -v 127 >/usr/share/nginx/html/index.html "
192.168.11.106 | CHANGED | rc=0 >>
192.168.11.108 | CHANGED | rc=0 >>
192.168.11.105 | CHANGED | rc=0 >>
192.168.11.107 | CHANGED | rc=0 >>
测试服务器是否全启动。
[root@node ~]# for i in 105 106 107 108
> do
> curl 192.168.11.$i
> done
192.168.11.105/23
192.168.11.106/23
192.168.11.107/23
192.168.11.108/23
增加负载均衡配置,进入调度器105,修改nginx.conf,将默认的location增加一行。
location / {
proxy_pass http://backend;
}
cat <<EOF >/etc/nginx/conf.d/upstream.conf
upstream backend {
server 192.168.11.106:80;
server 192.168.11.107:80;
server 192.168.11.108:80;
}
EOF
重新启动nginx
然后在调度器上运行
[root@localhost nginx]# for i in `seq 1 10 ` ; do curl 192.168.11.105; done
192.168.11.106/23
192.168.11.107/23
192.168.11.106/23
192.168.11.108/23
192.168.11.106/23
192.168.11.107/23
192.168.11.107/23
192.168.11.108/23
192.168.11.106/23
192.168.11.107/23
转发成功
Nginx负载均衡部署

1225





