1.案例概述
Haproxy是目前比较流行的一种群集调度工具,同类的调度工具备不少,如LVS和Nginx。相较而言,LVS性能最好,但搭建相对复杂;Nginx的upstream模块支持群集功能,但对群集节点健康检查功能不强,性能没有Haproxy好。html
2.案例前置知识
1)HTTP请求
经过URL访问网站使用的协议是HTTP协议,此类请求通常称为HTTP请求。HTTP请求的方式分为GET方式和POST方式。当使用浏览器访问某一个URL,会根据请求URL返回状态码,一般正常状态码为2x x,3x x(如200,301),若是出现异常会返回状态码为4x x,5x x(如400,500)。linux
2)负载均衡经常使用调度算法nginx
3.案例环境
1)编译安装nginx服务器web
(1)搭建nginx1,使用nginx-1.12.0.tar.gz安装包进行编译安装。 [root@localhost ~]# yum -y install pcre-devel zlib-devel [root@localhost ~]# useradd -M -s /sbin/nologin nginx [root@localhost media]# tar xf nginx-1.12.0.tar.gz -C /usr/src/ [root@localhost media]# cd /usr/src/nginx-1.12.0/ [root@localhost nginx-1.12.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx [root@localhost nginx-1.12.0]# make && make install
[root@localhost nginx-1.12.0]# cd /usr/local/nginx/html [root@localhost html]# echo 111 > test.html //创建测试页面 [root@localhost html]# /usr/local/nginx/sbin/nginx //启动nginx
2)编译安装Haproxyredis
使用haproxy-1.5.19.tar.gz安装包进行编译安装。 [root@localhost ~]# yum -y install pcre-devel bzip2-devel [root@localhost media]# tar xf haproxy-1.5.19.tar.gz -C /usr/src/ [root@localhost media]# cd /usr/src/haproxy-1.5.19/ [root@localhost haproxy-1.5.19]# make TARGET=linux26 //64位系统 [root@localhost haproxy-1.5.19]# make install
3)Haproxy服务配置
创建haproxy的配置文件算法
[root@localhost haproxy-1.5.19]# mkdir /etc/haproxy [root@localhost haproxy-1.5.19]# cp examples/haproxy.cfg /etc/haproxy/ //将haproxy.cfg文件复制到配置文件目录
4)Haproxy主配置需改动以下vim
[root@localhost ~]# vim /etc/haproxy/haproxy.cfg # this config needs haproxy-1.1.28 or haproxy-1.2.1 global log 127.0.0.1 local0 log 127.0.0.1 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 appli4-backup 0.0.0.0:80 //默认全部端口为80 option httpchk GET /index.html //HTTP的请求方式为GET balance roundrobin server inst1 192.168.1.20:80 check inter 2000 fall 3 //端口更改成80 server inst2 192.168.1.30:80 check inter 2000 fall 3 //BACKUP 表示为备用服务器
5)建立自启动脚本后端
[root@localhost haproxy-1.5.19]# cp /usr/src/haproxy-1.5.19/examples/haproxy.init /etc/init.d/haproxy [root@localhost haproxy-1.5.19]# ln -s /usr/local/sbin/haproxy /usr/sbin/haproxy [root@localhost haproxy-1.5.19]# chmod +x /etc/init.d/haproxy [root@localhost haproxy-1.5.19]# chkconfig --add /etc/init.d/haproxy [root@localhost haproxy-1.5.19]# /etc/init.d/haproxy start Starting haproxy (via systemctl): [ 肯定 ]
最后测试web群集只需在两台nginx服务器上echo两条测试文件就能够啦!