Skip to main content

Haproxy负载均衡

Haproxy负载均衡

简介

HAProxy是由C语言编写基于事件驱动模型的一款高效稳定、功能强大的负载均衡软件,其性能可媲美商业负载均衡软件,不过在最新的版本中HAProxy已经分为社区版本和企业版,社区版完全免费,企业版有丰富的额外功能。

  • 优点

◆支持虚拟主机,通过frontend指令来实现。

◆能弥补Nginx的一些缺点比如Session的保持、Cookie的引导等工作。

◆支持后端服务器健康检查,自动实现故障转移。

◆它跟LVS一样,本身仅仅就只是一款负载均衡软件,单纯从效率上来讲HAProxy更会比Nginx有更出色的负载均衡速度,在并发处理上也是优于Nginx。

◆同时支持四层和七层代理模式。

◆能对请求的url和header中的信息做匹配,更细粒度的七层负载均衡。

◆自带监控管理web页面。

◆能从进出两个方向修改http头信息。

◆同样支持多种负载均衡算法。

  • 缺点

◆重载配置的功能需要重启进程,虽然也是soft restart,但没有Nginx的reaload更为平滑和友好。

◆不支持HTTP cache功能。

安装

yum install haproxy -y

systemctl stop firewalld

systemctl disable firewalld

setenforce 0

配置

配置文件:/etc/haproxy/haproxy.cfg。

:::note haproxy配置文件可分为全局配置(globalsettings)和代理配置(proxies),而代理配置包含defaults、frontend、backend、listen。

■global settings:全局参数配置,用于定义haproxy进程管理安全及性能相关参数。

■defaults :默认配置参数,下面的段继承该配置,名称是可选的,默认配置参数可由下一个"defaults"重新设定。

■frontend :前端配置,定义一系列监听的套接字,这些套接字可接受客户端请求并与之建立连接,可以监听多个端口。

■backend :后端配置,定义后台服务器,前端代理服务器将会把客户端的请求调度至这些服务器,类似nginx中的upstream。

■listen :定义一组前端和后端的完整代理,可理解为frontend+backend,通常用于TCP流量代理。

■name名称必须由大写和小写字母、数字、'-'、'_'、'.'组成。 :::

以下是一个配置样例:

#---------------------------------------------------------------------

Example configuration for a possible web application. See the

full configuration options online.

https://www.haproxy.org/download/1.8/doc/configuration.txt

#---------------------------------------------------------------------

global

log         127.0.0.1 local2

chroot      /var/lib/haproxy

pidfile /var/run/haproxy.pid

stats socket   /var/run/haproxy.stat mode 600 level admin

user        haproxy

group       haproxy

daemon

maxconn     4000

defaults

mode                 http

log                   global

option                 httplog

option                 dontlognull

retries                 3

timeout http-request      5s

timeout queue           1m

timeout connect          5s

timeout client           1m

timeout server           1m

timeout http-keep-alive 5s

timeout check           5s

maxconn 3000

stats uri /stats

frontend main

bind *:80

default_backend         http_back

backend http_back

balance     roundrobin

server  node1 127.0.0.1:5001 check

server  node2 127.0.0.1:5002 check

server  node3 127.0.0.1:5003 check

server  node4 127.0.0.1:5004 check

功能使用

http负载均衡集群

177环境配置。

表4.1负载均衡环境配置

节点类型 IP地址 安装软件

分发节点
192.168.0.10 haproxy

服务节点
192.168.0.20 httpd

服务节点
192.168.0.30 httpd

178HAProxy配置:在“/etc/haproxy/haproxy.cfg”中,写入如下内容。

global

(略)

defaults

(略)

frontend http

bind 0.0.0.0:80

default_backend http_back

backend http_back

server s1 192.168.0.20:80 weight 3 check

server s2 192.168.0.30:80 weight 3 check

179执行如下命令,重启HAProxy服务。

systemctl restart haproxy.service

180服务节点配置:分别在两个服务节点执行如下命令,安装httpd,并启动httpd。

sudo yum install httpd php -y

sudo systemctl stop firewalld

sudo systemctl disable firewalld

setenforce 0

sudo echo “${ip}” > /var/www/html/index.html

sudo systemctl start httpd

181访问HAProxy:访问http://192.168.0.10时,HAProxy会将请求依次分发给http://192.168.0.20和http://192.168.0.30。

182访问http://192.168.0.10/stats,查看服务器状态。

mysql双主高可用

183环境配置。

表4.1mysql双主高可用环境配置

节点类型 IP地址 安装软件

分发节点
192.168.0.10 haproxy

服务节点
192.168.0.20 mariadb

服务节点
192.168.0.30 mariadb

184HAProxy配置:在“/etc/haproxy/haproxy.cfg”中,写入如下内容。

global

(略)

defaults

(略)

listen mysql

    bind 0.0.0.0:7306

    mode tcp

    balance roundrobin

    server mysql1 192.168.0.20:3306

    server mysql2 192.168.0.30:3306

listen stats

    bind 0.0.0.0:80

185执行如下命令,重启HAProxy服务。

systemctl restart haproxy.service

netstat -plantu | grep 7306

186服务节点配置:分别在两个服务节点执行如下命令。

yum install mariadb mariadb-server -y

systemctl stop firewalld

systemctl disable firewalld

setenforce 0

systemctl start mariadb

mysql -uroot -p

MariaDB [mysql]> GRANT ALL ON . TO 'haproxy'@'%' IDENTIFIED BY '123456';

MariaDB [mysql]> FLUSH PRIVILEGES;

187执行如下命令,在haproxy远程登录到mysql服务器。

yum install -y mysql (若没有mysql客户端,则需要安装)

mysql -uhaproxy -p123456 -h 192.168.0.20

mysql -uhaproxy -p123456 -h 192.168.0.30

Type 'help;' or"h'for help.Type 'c'to clear the current input statement. MariaDB [(none)]>)

188在其他服务器通过haproxy登录mysql:在其他的服务器上输入haproxy的服务器地址192.168.0.10,看是否能连接到数据库。7306是在配置文件中设置的端口,通过haproxy的7306端口访问mysql的3306端口。

Type 'he1p;or 'h'for help.Type 'c'to clear the current input statement. MariaDB [(none)]>quit Bye)

189浏览器访问http://192.168.0.10/stats,出现下图所示信息。

active UP, going down backup UP,going down uptime = 0d Oh00m16s active DOWN,going up backup DOWN,going up system limits: memmax = unlimited; ulimit,n= 8030 not checked active or backup DOWN maxsock =8030;maxconn =4000;maxpipes=0 active or backup DOWN for maintenance (MAINT) current conns =2; current pipes= 0/0; conn rate = 1/sec; bit rate = 0.000 kbps Running tasks: 1/16;idle = 100% active or backup SOFT STOPPED for maintenance Note: "NOLB"/"DRAIN"= UP with load-balancing disabled. mysql Queue Session rate Sessions Bytes Denied Errors Warnings Cur Max Limit Cur Max Limit Cur Max Limit Total LbTot Last In Out Req Resp Reg Conn Resp Retr Redis Status LastChk Frontend 3000 0 OPEN 0 0 0 0 0 0 0 0 0 0 mysql1 0 0 0 0 0 0 0 ? 0 0 0 0 0 0 0 no check 0 0 0 mysql2 0 0 0 0 0 0 0 ? 0 0 0 0 0 no check Backend 0 0 0 0 0 0 300 0 0 ? 0 0 0 0 0 0 0 0 16s UP stats Queue Session rate Sessions Denied Errors Warnings Bytes Limit Status LastChl Cur Max Limit Cur Max Limit Cur Max Total LbTot Last In Out Req Resp Req Conn Resp Retr Redis Frontend 2 3000 7 1652 1185 OPEN 0 0 Backend 0 300 0 1652 1185 16s UP 0 0 2 0 1 4 0s 0 0 4 0 0 0)

HAProxy动静分离

动静分离原理:将保存静态页面的服务器和动态页面的服务器分成2类,HAProxy根据用户的URL当中的后缀来区分是静态页面还是动态页面,HAProxy工作在OSI7层下。

动静分离过程:首先用户会先去请求首页,首页会返回整个页面的框架,用户浏览器会解析到还有很多资源需要再次向WEB发起请求,例如xxx.jpg等html资源标签。此时,HAProxy收到请求为xxx/xxx.jpg的请求后会判断为.JPG后缀的资源是静态页面,会向后端的静态页面发起请求,最后交给用户;如果请求的是.php结尾的则会调度到动态页面的节点中去,继而实现了动静分离效果。

190环境配置

表4.1HAProxy动静分离环境配置

节点类型 IP地址 安装软件

分发节点
192.168.0.10 haproxy

静态节点
192.168.0.20 httpd

动态节点
192.168.0.30 php、httpd

191haproxy节点配置:在“etc/haproxy/haproxy.cfg”中,写入如下内容。

global

(略)

defaults

(略)

frontend public

    bind            192.168.0.10:80 name clear

    use_backend     dynamic if { path_end .php }

    default_backend static

backend static

    balance         roundrobin

    server          web1 192.168.0.20:80 check inter 1000

backend dynamic

    balance         roundrobin

    server          web2 192.168.0.30:80 check inter 1000

192配置服务节点。

  • 静态节点:

[root@localhost html]# yum install httpd -y

[root@localhost html]# pwd

/var/www/html

[root@localhost html]# cat index.html

    <img src="/icons/123.jpg"/>

[root@localhost html]# cp 123.jpg /usr/share/httpd/icons/

[root@localhost html]# systemctl restart httpd

  • 动态节点:

[root@localhost html]# yum install php httpd -y

[root@localhost html]# pwd

/var/www/html

[root@localhost html]# cat index.php

<?php phpinfo();?>

[root@localhost html]# systemctl restart httpd.service

193执行如下命令,重启HAProxy服务。

[root@localhost html]# systemctl restart haproxy.service

194访问HAProxy:关闭防火墙,浏览器访问192.168.0.10,默认打开静态节点的界面。

195输入192.168.0.10/index.php,则打开的是动态节点的php界面。

/etc Loaded Configuration File /etc/php.ini Scan this dir for additional.ini files /etc/php.d Additional.ini fles parsed /etc/php.d/10-opcache.ini, etc/php.d/20-bcmath.ini,/etc/php.d/20-bz2.in,/tc/php.d/20-calendar.ini, /etc/php.d/20-ctype.ini,/etc/php.d/20-curl.ini, /etc/php.d/20-dba.ini,/etc/php.d/20-dom.ini /etc/pp.d/20-enhantini,/et/php.d/20-exifin,/etc/php.d/20-fleinfo.in,/etc/php.d/20-ftp.in; /etc/php.d/20-gd.ini,/etc/php.d/20-gettext.ini, /etc/php.d/20-gmp.ini,/etc/php.d/20-iconv.ini, /etc/php.d/20-intl.ini,/etc/php.d/20-json.ini,/etc/php.d/20-ldap.ini,/etc/php.d/20-mbstring.ini, /etc/php.d/20-mysqlnd.ini,/etc/php.d/20-odbc.ini,/etc/php.d/20-pdo.ini,/etc/php.d/20-pgsql.ini, /etc/php.d/20-phar.ini,/etc/php.d/20-posix.ini,/etc/php.d/20-recode.ini,/etc/php.d/20-shmop.ini, //pp.d/2-siplxml.n,/c/php./2-nmp.in,/php.d/20-soap.ini,/etc/php.d/20-ockets.in; /etc/php.d/20-sqlite3.ini,/etc/php.d/20-sysvmsg.ini, /etc/php.d/20-sysvsem.ini,/etc/php.d/20- sysvshm.inj,/etc/php.d/20-tidy.ini,/etc/php.d/20-tokenizer.in,/etc/php.d/20-xml.ini,/etc/php.d/20- xmlwriter.ini,/php.d/20-xslin,/c/php.d/30-mysqlini,/t/php.d/30-pdo_mysql.ini,/etc/php.d/30- pdo_odbc.ini,/etc/php.d/30-pdo_pgsql.ini, /etc/php.d/30-pdo_sqlite.ini, /etc/php.d/30-wddx.ini, /etc/php.d/30-xmlreader.ini,/etc/php.d/30-xmlrpc.ini, /etc/php.d/guestfs_php.ini PHP API 20170718)

196查看服务节点状态:浏览器访问http://192.168.0.10/stats,显示如下图所示的信息。

active UP, going down backup UP, going down uptime = 0d Oh02m23s active DOWN, going up backup DOWN, going up system limits: memmax = unlimited; ulimit-n= 8031 active or backup DOWN not checked maxsock = 8031;maxconn =4000;maxpipes=0 current conns = 2; current pipes = 0/0; conn rate = 2/sec; bit rate = 0.000 kbps active or backup DOWN for maintenance (MAINT) Running tasks: 1/19; idle = 100% active or backup SOFT STOPPED for maintenance Note: "NOLB""DRAIN"= UP with load-balancing disabled. public Queue Session rate Sessions Bytes Denied Errors Warnings Cur Max Limit Cur Max Limit Cur Max Limit Total LbTot Last In Out Req Resp Req Conn Resp Retr Redis Status L Frontend 2 2 2 2 3000 6 1221 197862 0 0 2 OPEN static Queue Session rate Sessions Bytes Denied Errors Warnings Cur Max Limit Cur Max Limit Cur Max Limit Total LbTot Last In Out Req Resp Req Conn Resp Retr Redis Status Las 2m23s UP L4OK web1 0 0 0 0 1 1 1m32s 406 248 0 0 0 0 0 Backend 0 0 0 1 0 1 300 1 1 1m32s 406 248 0 0 0 0 0 0 2m23s UP dynamic Queue Session rate Sessions Bytes Denied Errors Warnings Out Cur Max Limit Cur Max Limit Cur Max Limit Total LbTot Last In Req Resp Req Conn Resp Retr Redis Status L 2m23s UP L4C web2 0 0 0 2 0 2 2 1m26s 815 197140 0 0 0 0 0 Backend 0 0 0 2 0 300 2 2 1m26s 815 197140 0 0 0 0 0 0 2m23s UP 1)