Haproxy解析
阅读原文时间:2023年09月22日阅读:1

简单介绍

HAProxy是一款提供高可用性、负载均衡以及基于TCP和HTTP应用的代理软件,HAProxy是全然免费的、借助HAProxy能够高速而且可靠的提供基于TCP和HTTP应用的代理解决方式。HAProxy适用于那些负载较大的web网站,这些网站通常又须要会话保持或七层处理。 HAProxy能够支持数以万计的并发连接,而且HAProxy的执行模式使得它能够非常easy安全的整合进架构中,同一时候能够保护webserver不被暴露到网络上。

安装与管理

1)         安装步骤參考例如以下,将软件上传到/opt目录下

cd /opt

tar zxvf haproxy-1.4.9.tar.gz   

cd haproxy-1.4.9

make TARGET=linux26 PREFIX=/opt

make install PREFIX=/opt

2)         Haproxy管理

若haproxy已经配置完成,參考例如以下命令,启动

cd /opt/haproxy/sbin

./haproxy -f haproxy.cfg

输入usernamepassword,在例如以下页面进行状态监控

http://x.x.x.x:1080/haproxy-stats

加入开机自启服务。将haproxy启动命令加入到/etc/rc.local文件里。如

/opt/haproxy/sbin/haproxy -f haproxy.cfg

配置优化

1)         Haproxy配置优化说明

參数配置演示样例

规则说明

maxconn 32768

最大连接数

daemon

推荐使用守护进程模式启动

nbproc 8

负载均衡的并发进程数

retries 3

重试次数

2)         Haproxy配置(haproxy.cfg)演示样例

创建配置文件

cd  /opt/haproxy

touch  haproxy.cfg

配置演示样例

global

log 127.0.0.1    local0

maxconn 4096

chroot /opt/haproxy

#      uid www

#      gid www

uid  0

gid  0

daemon

nbproc 2

pidfile logs/haproxy.pid

#debug

#quiet

defaults

log     127.0.0.1       local3

mode    http

option  httplog

option  httpclose

option  dontlognull

option  forwardfor

option  redispatch

retries 2

maxconn 2000

balance roundrobin

stats enable

stats   uri     /haproxy-stats

contimeout      5000

clitimeout      50000

srvtimeout      50000

listen  web_proxy 0.0.0.0:1080

option  httpchk GET /ping.jsp

server  s1 192.168.15.110:8080 weight 3 check

server  s3 192.168.15.111:8080 weight 3 check

listen  mysql_proxy 0.0.0.0:3306

server  s1 192.168.15.110:3306 weight 3 check

server  s3 192.168.15.111:3306 weight 3 check

写在前面的话。《Haproxy配置文件具体解释》文档部分信息来自网络,同一时候參考过官方的架构指南,在此很感谢zero提供的文档。以及在学习Haproxy过程中的帮助。

  1. #/usr/local/sbin/haproxy -f /etc/haproxy/haproxy.cfg -st `cat /var/run/haproxy.pid`
  2. ####################全局配置信息########################
  3. #######參数是进程级的,通常和操作系统(OS)相关#########
  4. global
  5. maxconn 20480                   #默认最大连接数
  6. log 127.0.0.1 local3            #[err warning info debug]
  7. chroot /var/haproxy             #chroot执行的路径
  8. uid 99                          #所属执行的用户uid
  9. gid 99                          #所属执行的用户组
  10. daemon                          #以后台形式执行haproxy
  11. nbproc 1                        #进程数量(能够设置多个进程提高性能)
  12. pidfile /var/run/haproxy.pid    #haproxy的pid存放路径,启动进程的用户必须有权限訪问此文件
  13. ulimit-n 65535                  #ulimit的数量限制
  14. #####################默认的全局设置######################
  15. ##这些參数能够被利用配置到frontend,backend,listen组件##
  16. defaults
  17. log global
  18. mode http                       #所处理的类别 (#7层 http;4层tcp  )
  19. maxconn 20480                   #最大连接数
  20. option httplog                  #日志类别http日志格式
  21. option httpclose                #每次请求完成后主动关闭http通道
  22. option dontlognull              #不记录健康检查的日志信息
  23. option forwardfor               #假设后端服务器须要获得client真实ip须要配置的參数,能够从Http Header中获得clientip
  24. option redispatch               #serverId相应的服务器挂掉后,强制定向到其它健康的服务器
  25. option abortonclose             #当服务器负载非常高的时候,自己主动结束掉当前队列处理比較久的连接
  26. stats refresh 30                #统计页面刷新间隔
  27. retries 3                       #3次连接失败就觉得服务不可用,也能够通过后面设置
  28. balance roundrobin              #默认的负载均衡的方式,轮询方式
  29. #balance source                  #默认的负载均衡的方式,类似nginx的ip_hash
  30. #balance leastconn               #默认的负载均衡的方式,最小连接
  31. contimeout 5000                 #连接超时
  32. clitimeout 50000                #client超时
  33. srvtimeout 50000                #服务器超时
  34. timeout check 2000              #心跳检測超时
  35. ####################监控页面的设置#######################
  36. listen admin_status                    #Frontend和Backend的组合体,监控组的名称,按需自己定义名称
  37. bind 0.0.0.0:65532             #监听port
  38. mode http                      #http的7层模式
  39. log 127.0.0.1 local3 err       #错误日志记录
  40. stats refresh 5s               #每隔5秒自己主动刷新监控页面
  41. stats uri /admin?stats         #监控页面的url
  42. stats realm itnihao\ itnihao   #监控页面的提示信息
  43. stats auth admin:admin         #监控页面的用户和passwordadmin,能够设置多个username
  44. stats auth admin1:admin1       #监控页面的用户和passwordadmin1
  45. stats hide-version             #隐藏统计页面上的HAproxy版本号信息
  46. stats admin if TRUE            #手工启用/禁用,后端服务器(haproxy-1.4.9以后版本号)
  47. errorfile 403 /etc/haproxy/errorfiles/403.http
  48. errorfile 500 /etc/haproxy/errorfiles/500.http
  49. errorfile 502 /etc/haproxy/errorfiles/502.http
  50. errorfile 503 /etc/haproxy/errorfiles/503.http
  51. errorfile 504 /etc/haproxy/errorfiles/504.http
  52. #################HAProxy的日志记录内容设置###################
  53. capture request  header Host           len 40
  54. capture request  header Content-Length len 10
  55. capture request  header Referer        len 200
  56. capture response header Server         len 40
  57. capture response header Content-Length len 10
  58. capture response header Cache-Control  len 8
  59. #######################站点监測listen配置#####################
  60. ###########此使用方法主要是监控haproxy后端服务器的监控状态############
  61. listen site_status
  62. bind 0.0.0.0:1081                    #监听port
  63. mode http                            #http的7层模式
  64. log 127.0.0.1 local3 err             #[err warning info debug]
  65. monitor-uri /site_status             #站点健康检測URL,用来检測HAProxy管理的站点能否够用。正常返回200,不正常返回503
  66. acl site_dead nbsrv(server_web) lt 2 #定义站点down时的策略当挂在负载均衡上的指定backend的中有效机器数小于1台时返回true
  67. acl site_dead nbsrv(server_blog) lt 2
  68. acl site_dead nbsrv(server_bbs)  lt 2
  69. monitor fail if site_dead            #当满足策略的时候返回503,网上文档说的是500。实际測试为503
  70. monitor-net 192.168.16.2/32          #来自192.168.16.2的日志信息不会被记录和转发
  71. monitor-net 192.168.16.3/32
  72. ########frontend配置############
  73. #####注意,frontend配置里面能够定义多个acl进行匹配操作########
  74. frontend http_80_in
  75. bind 0.0.0.0:80      #监听port。即haproxy提供web服务的port,和lvs的vipport类似
  76. mode http            #http的7层模式
  77. log global           #应用全局的日志配置
  78. option httplog       #启用http的log
  79. option httpclose     #每次请求完成后主动关闭http通道,HA-Proxy不支持keep-alive模式
  80. option forwardfor    #假设后端服务器须要获得client的真实IP须要配置次參数。将能够从Http Header中获得clientIP
  81. ########acl策略配置#############
  82. acl itnihao_web hdr_reg(host) -i ^(www.itnihao.cn|ww1.itnihao.cn)$
  83. #假设请求的域名满足正則表達式中的2个域名返回true -i是忽略大写和小写
  84. acl itnihao_blog hdr_dom(host) -i blog.itnihao.cn
  85. #假设请求的域名满足www.itnihao.cn返回true -i是忽略大写和小写
  86. #acl itnihao    hdr(host) -i itnihao.cn
  87. #假设请求的域名满足itnihao.cn返回true -i是忽略大写和小写
  88. #acl file_req url_sub -i  killall=
  89. #在请求url中包括killall=,则此控制策略返回true,否则为false
  90. #acl dir_req url_dir -i allow
  91. #在请求url中存在allow作为部分地址路径,则此控制策略返回true,否则返回false
  92. #acl missing_cl hdr_cnt(Content-length) eq 0
  93. #当请求的header中Content-length等于0时返回true
  94. ########acl策略匹配相应#############
  95. #block if missing_cl
  96. #当请求中header中Content-length等于0阻止请求返回403
  97. #block if !file_req || dir_req
  98. #block表示阻止请求,返回403错误,当前表示假设不满足策略file_req,或者满足策略dir_req,则阻止请求
  99. use_backend  server_web  if itnihao_web
  100. #当满足itnihao_web的策略时使用server_web的backend
  101. use_backend  server_blog if itnihao_blog
  102. #当满足itnihao_blog的策略时使用server_blog的backend
  103. #redirect prefix http://blog.itniaho.cn code 301 if itnihao
  104. #当訪问itnihao.cn的时候,用http的301挑转到http://192.168.16.3
  105. default_backend server_bbs
  106. #以上都不满足的时候使用默认server_bbs的backend
  107. ##########backend的设置##############
  108. #以下我将设置三组服务器 server_web,server_blog。server_bbs
  109. ###########################backend server_web#############################
  110. backend server_web
  111. mode http            #http的7层模式
  112. balance roundrobin   #负载均衡的方式,roundrobin平均方式
  113. cookie SERVERID      #同意插入serverid到cookie中,serverid后面能够定义
  114. option httpchk GET /index.html #心跳检測的文件
  115. server web1 192.168.16.2:80 cookie web1 check inter 1500 rise 3 fall 3 weight 1
  116. #服务器定义,cookie 1表示serverid为web1,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。
  117. #fall 3是3次失败觉得服务器不可用。weight代表权重
  118. server web2 192.168.16.3:80 cookie web2 check inter 1500 rise 3 fall 3 weight 2
  119. #服务器定义。cookie 1表示serverid为web2,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用,
  120. #fall 3是3次失败觉得服务器不可用,weight代表权重
  121. ###################################backend server_blog###############################################
  122. backend server_blog
  123. mode http            #http的7层模式
  124. balance roundrobin   #负载均衡的方式,roundrobin平均方式
  125. cookie SERVERID      #同意插入serverid到cookie中,serverid后面能够定义
  126. option httpchk GET /index.html #心跳检測的文件
  127. server blog1 192.168.16.2:80 cookie blog1 check inter 1500 rise 3 fall 3 weight 1
  128. #服务器定义。cookie 1表示serverid为web1,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。fall 3是3次失败觉得服务器不可用,weight代表权重
  129. server blog2 192.168.16.3:80 cookie blog2 check inter 1500 rise 3 fall 3 weight 2
  130. #服务器定义,cookie 1表示serverid为web2,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。fall 3是3次失败觉得服务器不可用。weight代表权重
  131. ###################################backend server_bbs###############################################
  132. backend server_bbs
  133. mode http            #http的7层模式
  134. balance roundrobin   #负载均衡的方式,roundrobin平均方式
  135. cookie SERVERID      #同意插入serverid到cookie中。serverid后面能够定义
  136. option httpchk GET /index.html #心跳检測的文件
  137. server bbs1 192.168.16.2:80 cookie bbs1 check inter 1500 rise 3 fall 3 weight 1
  138. #服务器定义。cookie 1表示serverid为web1,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用。fall 3是3次失败觉得服务器不可用,weight代表权重
  139. server bbs2 192.168.16.3:80 cookie bbs2 check inter 1500 rise 3 fall 3 weight 2
  140. #服务器定义,cookie 1表示serverid为web2,check inter 1500是检測心跳频率rise 3是3次正确觉得服务器可用,fall 3是3次失败觉得服务器不可用,weight代表权重

样例

mysql

1. 加入监控MySQL状态的port

# vi /etc/services

mysqlcheck 6033/tcp # MySQL status check

2. 使用xinetd守护进程执行MySQL状态检測

# cat /etc/xinetd.d/mysqlchk

service mysqlcheck
{
disable = no
flags = REUSE
socket_type = stream
port = 6033
wait = no
user = root
server = /usr/local/haproxy/sbin/mysqlchk_status.sh
log_on_failure += USERID
}

3. 状态检測脚本

# vi /usr/local/haproxy/sbin/mysqlchk_status.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#/bin/bash
MYSQL_HOST="localhost"
MYSQL_PORT="3306"
MYSQL_USERNAME="root"
MYSQL_PASSWORD="123456"
 
ERROR_MSG=/usr/bin/mysql --host=$MYSQL_HOST --port=$MYSQL_PORT --user=$MYSQL_USERNAME --password=$MYSQL_PASSWORD -e "show databases;"
 
if [ "$ERROR_MSG" != "" ]
then
# mysql is fine, return http 200
/bin/echo -e "HTTP/1.1 200 OK\r\n"
/bin/echo -e "Content-Type: Content-Type: text/plain\r
\n
"
/bin/echo -e "\r\n"
/bin/echo -e "MySQL is running.\r
\n
"
/bin/echo -e "\r\n"
else
# mysql is fine, return http 503
/bin/echo -e "HTTP/1.1 503 Service Unavailable\r
\n
"
/bin/echo -e "Content-Type: Content-Type: text/plain\r\n"
/bin/echo -e "\r
\n
"
/bin/echo -e "MySQL is *down*.\r\n"
/bin/echo -e "\r
\n
"
fi

# chown haproxy.haproxy /usr/local/haproxy/sbin/mysqlchk_status.sh

4. HAproxy日志

# touch /var/log/haproxy.log

# chown haproxy.haproxy /var/log/haproxy.log

编辑/etc/syslog.conf文件,加入例如以下语句

local0.* /var/log/haproxy.log

5. HAProxy配置文件

[root@localhost htdocs]# cat /usr/local/haproxy/conf/haproxy.conf

global
maxconn 4096
daemon
pidfile /usr/local/haproxy/run/haproxy.pid
#debug
#quiet
user haproxy
group haproxy
 
defaults
log global
mode http
option httplog
option dontlognull
log 127.0.0.1 local0
retries 3
option redispatch
maxconn 2000
contimeout 5000
clitimeout 50000
srvtimeout 50000
 
listen admin_stats 192.168.0.1:80
mode http
stats uri /dbs
stats realm Global\ statistics
stats auth test:123456
 
listen proxy-mysql 0.0.0.0:23306
mode tcp
balance roundrobin
option httpchk OPTIONS * HTTP/1.1\r\nHost:\ www
server db01 192.168.0.1:3306 weight 1 check port 6033 inter 1s rise 2 fall 2
server db02 192.168.0.2:3306 weight 1 check port 6033 inter 1s rise 2 fall 2
option tcpka

6. HAProxy启动脚本

# cat /etc/init.d/haproxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

#! /bin/sh
set -e
 
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/haproxy/sbin
PROGDIR=/usr/local/haproxy
PROGNAME=haproxy
DAEMON=$PROGDIR/sbin/$PROGNAME
CONFIG=$PROGDIR/conf/$PROGNAME.conf
PIDFILE=$PROGDIR/run/$PROGNAME.pid
DESC="HAProxy daemon"
SCRIPTNAME=/etc/init.d/$PROGNAME
 
# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0
 
start()
{
echo -n "Starting $DESC: $PROGNAME"
$DAEMON -f $CONFIG
echo "."
}
 
stop(
)

{
echo -n "Stopping $DESC: $PROGNAME"
haproxy_pid=cat $PIDFILE
kill $haproxy_pid
echo "."
}
 
restart()
{
echo -n "Restarting $DESC: $PROGNAME"
$DAEMON -f $CONFIG -p $PIDFILE -sf $(
cat
$PIDFILE)
echo "."
}
 
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
exit 1
;;
esac
 
exit 0