1.需求:
在之前我们使用的keepalived+nginx的方案,架构如下:
该方案的缺点是资源使用率不高,只能在吞吐量不高的场景使用
第二种方案:haproxy+nginx,架构图如下:
这个会有单点故障,当单机haproxy宕机时,会导致珍格格服务不可用
最后一种也是最好的方案:keepalived+haproxy+nginx,架构图为:
既可以在高并发下使用,也解决了单点故障问题
在此次实验中,我们的IP有变化,如下:
VIP:11.0.1.100:8080
NODE1 :Real IP:11.0.1.17
VIP:11.0.1.100
Haproxy:0.0.0.0:8080
NODE2 :Real IP:11.0.1.16
VIP:11.0.1.100
Haproxy:0.0.0.0:8080
Nginx1:11.0.1.17:80
Nginx2:11.0.1.16:80
2.规划
我们可以在上一章的keepalived+nginx的基础上,在补充haproxy的方式实现高可用负载均衡架构
Hostname | IP | Node roles |
Keepalived-master | 11.0.1.17 | Keepalived(master), Nginx, HAProxy |
Keepalived-backup | 11.0.1.16 | Keepalived(backup), Nginx, HAProxy |
上一章的链接如下:keepalived+nginx实现高可用-CSDN博客
3.增加Haproxy
现在我们在前一阶段,添加Haproxy,实现双主负载均衡
3.1 两台服务器都安装haproxy
下载安装包:
wget http://download.openpkg.org/components/cache/haproxy/haproxy-3.0.3.tar.gz
解压:tar -zxvf haproxy-3.0.3.tar.gz
uname -a 确定linux内核,红帽7对应linux31
cd haproxy-3.0.3
make TARGET=linux31
开始安装:make install PREFIX=/opt/haproxy
创建日志目录:mkdir /opt/haproxy/logs
拷贝配置文件:cp examples/option-http_proxy.cfg /opt/haproxy/haproxy.cfg
编写服务脚本:
vim /etc/rc.d/init.d/haproxy
[root@localhost haproxy-3.0.3]# vim /etc/rc.d/init.d/haproxy
#!/bin/bash
#chkconfig: 2345 10 90
#description:haproxy
BASE_DIR="/opt/haproxy"
ARGV="$@"
start()
{
echo "START HAPoxy SERVERS"
$BASE_DIR/sbin/haproxy -f $BASE_DIR/haproxy.cfg
}
stop()
{
echo "STOP HAPoxy Listen"
kill -TTOU $(cat $BASE_DIR/logs/haproxy.pid)
echo "STOP HAPoxy process"
kill -USR1 $(cat $BASE_DIR/logs/haproxy.pid)
}
case $ARGV in
start)
start
ERROR=$?
;;
stop)
stop
ERROR=$?
;;
restart)
stop
start
ERROR=$?
;;
*)
echo "hactl.sh [start|restart|stop]"
esac
exit $ERROR
添加开机自启动:chmod +x /etc/rc.d/init.d/haproxy
chkconfig --add haproxy
3.2 修改haproxy配置文件
cat /opt/haproxy/haproxy.cfg
[root@localhost haproxy-3.0.3]# cat /opt/haproxy/haproxy.cfg
#
# demo config for Proxy mode
#
global
#maxconn 20000
#ulimit-n 16388
log 127.0.0.1 local0
uid 200
gid 200
chroot /opt/haproxy
daemon
frontend http_80_in
bind 0.0.0.0:8080
mode http
log global
option httplog
option dontlognull
maxconn 8000
timeout client 30s
# layer3: Valid users
#acl allow_host src 192.168.200.150/32
#http-request deny if !allow_host
# layer7: prevent private network relaying
#acl forbidden_dst url_ip 192.168.0.0/24
#acl forbidden_dst url_ip 172.16.0.0/12
#acl forbidden_dst url_ip 10.0.0.0/8
#http-request deny if forbidden_dst
default_backend webserver
backend webserver
mode http
timeout connect 5s
timeout server 5s
retries 2
# layer7: Only GET method is valid
acl valid_method method GET
http-request deny if !valid_method
# take IP address from URL's authority
# and drop scheme+authority from URI
http-request set-dst url_ip
http-request set-dst-port url_port
http-request set-uri %[pathq]
server next-hop 0.0.0.0
# layer7: protect bad reply
http-response deny if { res.hdr(content-type) audio/mp3 }
balance roundrobin
server server1 11.0.1.16:80 check
server server2 11.0.1.17:80 check
启动服务:systemctl start haproxy
3.3 测试
刷新后
验证成功