1.Haproxy简介及与Nginx区别
Haproxy提供高可用性、负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。Haproxy特别适用于那些负载特大的web站点,这些站点通常又需要会保持或七层处理。Haproxy运行在当前的硬件上,完全可以支持数以万计的并发连接。并且它的运行模式使得它可以很简单安全的整合进您当前的架构中,同时可以保护你的web服务器不被暴露到网络上。
与Nginx的区别
1.支持TCP与Http协议,工作在网络4层和7层
2.支持Session共享、Cookies引导
3.支持通过URL健康检测
4.支持8种负载均衡策略
5.支持心跳检测
6.HAProxy支持TCP协议的负载均衡转发,可以对MySQL读进行负载均衡,对后端的MySQL节点进行检测和负载均衡,大家可以用LVS+Keepalived对MySQL主从做负载均衡。
7.不支持 Http Cach
2.Haproxy安装脚本
#!/bin/bash
#function: 安装Haproxy
#author:
#####root判断#####
if
[ "$USER" != "root" ]
then
echo "错误:非root用户,权限不足!"
exit 0
fi
############防火墙与高级权限##########
systemctl stop firewalld && systemctl disable firewalld && echo "防火墙已经关闭"
sed -i 's/SELINUX=*/SELINUX=disabled/g' /etc/selinux/config && echo "关闭selinux"
###############检查网络连通是否正常############
ping -c 3 www.baidu.com
if
[ $? -eq 0 ]
then
echo -e "\n\033[32m-----------------------------------------------\033[0m"
echo -e "\033[32m网络畅通,即将安装服务\033[0m"
else
echo -e "\n\033[32m-----------------------------------------------\033[0m"
echo -e "\033[32m即将退出,请检查外网通讯 !\033[0m"
exit 1
fi
##################安装依赖包################
yum -y install pcre-devel bzip2-devel gcc gcc-c++ make
if
[ $? = 0 ]
then
echo "依赖包安装成功"
else
echo "依赖包安装失败"
exit 1
fi
############上传Haproxy安装包###########
HAPROXY="/root/haproxy-1.5.19.tar.gz"
if
[ ! -e $HAPROXY ]
then
echo "安装包不存在,请上传安装文件到/root/,上传完成再重新运行该脚本"
exit 1
fi
###########解压、安装##########
tar zxf HAPROXY && cd /root/haproxy-1.5.19
make TARGET=linux2628 ARCH=x86_64 && make install
if
[ $? = 0 ];
then
echo "编译安装已成功"
else
echo "编译安装失败"
exit 1
fi
sleep 2
###########修改Haproxy配置文件#########
mkdir /etc/haproxy
cp examples/haproxy.cfg /etc/haproxy/
cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak
read -ep "请输入web1节点的IP地址:" wed1
read -ep "请输入web2节点的IP地址:" wed2
cat > /etc/haproxy/haproxy.cfg <<EOF
# this config needs haproxy-1.1.28 or haproxy-1.2.1
global
log /dev/log local0 info
log /dev/log local1 notice
#log loghost local0 info
maxconn 4096
#chroot /usr/share/haproxy
uid 99
gid 99
daemon
#debug
#quiet
defaults
log global
mode http
option httplog
option dontlognull
retries 3
redispatch
maxconn 2000
contimeout 5000
clitimeout 50000
srvtimeout 50000
listen webcluster 0.0.0.0:80
option httpchk GET /test.html
balance roundrobin
server inst1 $wed1:80 check inter 2000 fall 3
server inst2 $wed2:80 check inter 2000 fall 3
EOF
#########给系统添加服务############
cp /root/haproxy-1.5.19/examples/haproxy.init /etc/init.d/haproxy
cd /etc/init.d/ && chmod +x haproxy
chkconfig --add /etc/init.d/haproxy
ln -s /usr/local/sbin/haproxy /usr/sbin/haproxy
#########启动Haproxy服务#########
/etc/init.d/haproxy start ###或 cd /etc/init.d/ service haproxy start
if
[ $? = 0 ];
then
echo "Haproxy服务已开启"
else
echo "Haproxy服务开启失败"
exit 1
fi
IP=$(hostname -I | awk '{print $1}' | awk -F '.' '{print $1"."$2"."$3"."$4}')
echo "Haproxy服务已部署完成,请用$IP访问网页!"