一、HAProxy
HAProxy提供高可用性、负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。HAProxy特别 适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。HAProxy运行在当前的硬件上,完全可以支持数以万计的并发连接。并且它的 运行模式使得它可以很简单安全的整合进您当前的架构中, 同时可以保护你的web服务器不被暴露到网络上。
二、环境配置
srever1:haproxy
server2/3:apache
1.安装haproxy:
1)下载解压paroxy包:
tar zxf haproxy-1.7.3.tar.gz
MakeFile:各个模块之间的调用
2. 制作rpm包并安装
注意: 有.spec文件,就可以把源码制作为rpm包
制作好后会生成rpmbuild的目录
cd haproxy-1.7.3
ls
find . -name *.spec #查看是否有.spec文件
yum install rpm-build pcre-devel gcc -y #安装制作rpm包的工具
rpmbuild -tb haproxy-1.7.3.tar.gz #制作rpm包
cd /root/rpmbuild/RPMS/x86_64
rpm -ivh haproxy-1.7.3-1.x86_64.rpm #安装haproxy
三、实现负载均衡
1.编辑配置文件,打开服务
cd /root/haproxy-1.7.3/examples/
cp -rp content-sw-sample.cfg /etc/haproxy/haproxy.cfg
cd /etc/haproxy/
vim haproxy.cfg
/etc/init.d/haproxy start
2.server2/3上安装httpd,并打开:
vim /var/www/html/index.html
server2
/etc/init.d/httpd start
vim /var/www/html/index.html
server3
/etc/init.d/httpd start
3.测试:
真机上:
curl 172.25.60.1
4.监控窗口:
打开firefox:http://172.25.60.1/admin/stats
按F5刷新,访问量是不断增加的:
停止server2的httpd服务:
增加自动更新时间和用户:
vim haproxy.cfg
/etc/init.d/haproxy restart
ctrl+shift+delete:清除浏览器缓存
四、日志和黑名单
1.日志
vim /etc/rsyslog.conf
/etc/init.d/rsyslog restart
2.黑名单
vim haproxy.cfg
acl blacklist src 172.25.60.250
http-request deny if blacklist
/etc/init.d/haproxy restart
server1上安装httod,并把端口改为8080:
yum install httpd -y
vim /var/www/html/index.html
vim /etc/httpd/conf/httpd.conf
136 Listen 8080
/etc/init.d/httpd start
vim haproxy.cfg
48 errorloc 403 http://172.25.60.1:8080/index.html
/etc/init.d/haproxy restart
测试:打开firefox:http://172.25.60.1/admin/stats
在黑名单里的主机访问会自动跳转到http://172.25.60.1:8080/index.html.
五、动静分离
访问静态的访问的是server2的默认发布页,访问以.php结尾的时,访问的是php动态页面。
1.编辑配置文件
vim haproxy.cfg
use_backend static if { path_end .php }
default_backend static
# The static backend backend for 'Host: img', /img and /css.
backend static
balance roundrobin
server web1 172.25.60.2:80 check inter 1000
# the application servers go here
backend dynamic
balance roundrobin
server web2 172.25.60.3:80 check inter 1000
/etc/init.d/haproxy restart
2.server3上下载php
yum install php -y
vim /var/www/html/index.php
<?php
phpinfo();
?>
/etc/init.d/httpd restart
3.测试:
在真机上:curl 172.25.60.1
打开firefox:http://172.25.60.1/index.php
六、读写分离
1.编辑配置文件
vim haproxy.cfg
acl write method POST
acl write method PUT
use_backend dynamic if write
default_backend static
# The static backend backend for 'Host: img', /img and /css.
backend static
balance roundrobin
server web1 172.25.60.2:80 check inter 1000
# the application servers go here
backend dynamic
balance roundrobin
server web2 172.25.60.3:80 check inter 1000
/etc/init.d/haproxy restart
2.在server2上上传两个php文件:
cd /var/www/html/
ls
chmod 777 index.php upload_file.php
vim upload_file.php
($_FILES["file"]["size"] < 2000000)) #扩大文件接收的数据
/etc/init.d/httpd restart
3.测试:
打开firefox:http://172.25.60.1/index.php
在server3上查看: