您的位置:首页 > 其它

haproxy

2017-10-18 15:21 211 查看
一、haproxy的介绍
HAProxy提供高可用性、负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,尤其适用于高负载且需要持久连接或7层处理机制的web站点。。Haproxy支持两种主要代理模式:第一个是4层tcp代理(例如:可用于邮件服务内部协议通信服务器、Mysql服务等)。第二个是7层代理(如HTTP代理)。在4层tcp代理模式下,Haproxy仅在客户端和服务器之间双向转发流量。但是在7层模式下Haproxy会分析应用层协议,并且能通过运行、拒绝、交换、增加、修改或者删除请求(request)或者回应(reponse)里指定内容来控制协议。
二、haproxy的配置
haproxy的配置文件/etc/haproxy/haproxy.cfg,分为5个部分
1、global:参数是进程级的,通常是和操作系统相关。这些参数一般只设置一次,如果配置无误,就不需要再次进行修改
2、defaults:配置默认参数,这些参数可以被用到frontend,backend,Listen组件
3、frontend:用于定义一系列监听的套接字,这些套接字可接受客户端请求并与之建立连接
4、backend:用于定义一系列“后端”服务器,代理将会将对应客户端的请求转发至这些服务器
5、Listen:通过关联“前端”和“后端”定义了一个完整的代理,通常只对TCP流量有用
下面为默认配置文件:
global
log         127.0.0.1 local2                #全局syslog服务器,最多可以定义两个
chroot      /var/lib/haproxy
pidfile     /var/run/haproxy.pid
maxconn     4000                            #最大连接数
user        haproxy
group       haproxy
daemon
stats socket /var/lib/haproxy/stats
defaults
mode                    http                #代理模式 (tcp|http),混合模式无需设置mode
log                     global              #定义全局日志
option                  httplog            #启用记录HTTP请求、会话状态和计时器的功能。混合模式还需要tcplog
option                  dontlognull        #不记录健康检查的日志信息
option http-server-close                    #每次请求完毕后主动关闭http通道
option forwardfor       except 127.0.0.0/8  #如果后端服务器需要获得客户端真实ip需要配置的参数,可以从Http Header中获得客户端ip
option                  redispatch        #serverId对应的服务器挂掉后,强制定向到其他健康的服务器
retries                 3                 #失败连接次数3
timeout http-request    10s                #http请求超时
timeout queue           1m                 #队列超时
timeout connect         10s                #连接超时时间
timeout client          1m                 #客户端连接超时
timeout server          1m                 #服务器连接超时
timeout http-keep-alive 10s                #持久连接连接超时
timeout check           10s                #心跳检测超时
maxconn                 3000                #最大连接数
frontend  main *:5000
acl url_static       path_beg       -i /static /images /javascript /stylesheets
acl url_static       path_end       -i .jpg .gif .png .css .js
use_backend static          if url_static     #acl
default_backend             app               #使用的后端服务器组
backend static                                    #
balance     roundrobin                        #负载均衡算法
server      static 127.0.0.1:4331 check
backend app
balance     roundrobin
server  app1 127.0.0.1:5001 check
server  app2 127.0.0.1:5002 check
server  app3 127.0.0.1:5003 check
server  app4 127.0.0.1:5004 check
关于默认配置文件的补充:
1、log
将log记录在/var/log/haproxy.log
编辑 vim /etc/rsyslog.conf,增加log2* /var/log/haproxy.log,重启日志 service rsyslog restart
/etc/sysconfig/rsyslog
SYSLOGD_OPTIONS="-r -m 0 -c 2"
#-c 2 使用兼容模式,默认是 -c 5
#-r 开启远程日志
#-m 0 标记时间戳。单位是分钟,为0时,表示禁用该功能
/etc/rsyslog.conf

$ModLoad imudp
$UDPServerRun 514
2、balance
定义负载均衡算法,可以用defaults,backed及listen中,算法常用的有以下几种
1)、roundrobin:基于权重进行轮询,可以在运行时进行权重调整。但是,设计上每个后端服务器仅能最多支持4128个连接
2)、static-rr:静态的基于权重轮询,运行时调整权重无效,但是没有对连接数的限制
3)、leastconn:请求被发往后端最少连接数目的服务器,可以动态调整权重,在保持较长回话的场景中推荐使用此算法
4)、source:类似于niginx的ip_hash ,默认为静态
5)、uri:对uri ?号之前的部分或者整个uri进行hash算后除模派发至相应服务器,适用于代理缓存及反病毒代理
URL Syntax: <scheme>://<host>:<port>/<path>;<params>?<query>#<frag> http://www.wlw.com/test/go;type=s6)、url_param:通过<argument>为URL指定的参数在每个HTTP GET请求中将会被检索;如果找到了指定的参数且其通过等于号“=”被赋予了一个值,那么此值将被执行hash运算并被服务器的总权重相除后派发至某匹配的服务器;此算法可以通过追踪请求中的用户标识进而确保同一个用户ID的请求将被送往同一个特定的服务器,除非服务器的总权重发生了变化;如果某请求中没有出现指定的参数或其没有有效值,则使用轮叫算法对相应请求进行调度;此算法默认为静态的
7)、hdr(<name>):对于每个HTTP请求,通过<name>指定的HTTP首部将会被检索;如果相应的首部没有出现或其没有有效值,则使用轮叫算法对相应请求进行调度;其有一个可选选项“use_domain_only”,可在指定检索类似Host类的首部时仅计算域名部分以降低hash算法的运算量;此算法默认为静态的
3、hash_type
map_based:默认 不适用于后端为缓存服务器

consistent:一致性hash 适用于后端为缓存服务器

4、bind
用于frontend和listen中,格式为bind [<address>]:<port_range> [, ...]
5、default_backend
没有匹配use_backend的情况下默认使用的后端
6、server

server <name> <address>[:port] [param*]
[param*]参数
1)backup,负载均衡的备用服务器
2)check,进行健康检测,还可以根据另外的参数进行定制 inter <delay> 时间间隔 rise <count>从离线到正常的检测次数 fall<count>从正常到离线的检测次数
后端check的方法
option httpchk:请求首页,对方响应200即为成功
option httpchk <uri>:指定的uri,对方响应200即为成功
option httpchk <method> <uri>:指定方法和uri
option httpchk <method> <uri> <version>:不能用于frontend段
3)cookie <value>:为指定server设定cookie值,此处指定的值将在请求入站时被检查,第一次为此值挑选的server将在后续的请求中被选中,其目的在于实现持久连接的功能;基于cookie会话的源绑定。
backend static
balance    roundrobin
cookie    webser insert nocache
server    serv1  192.168.0.102:80 check port 80 weight 2 cookie serv1
server    serv2  192.168.0.103:80 check port 80 weight 1 cookie serv2



4) weight <weight>:权重,默认为1,最大值为256,0表示不参与负载均衡;
5)redir <prefix>:启用重定向功能,将发往此服务器的GET和HEAD请求均以302状态码响应;需要注意的是,在prefix后面不能使用/,且不能使用相对地址,以免造成循环
server    serv1  192.168.0.102:80 check port 80 redir http://192.168.0.104[/code]6)server 绑定端口后前端bind多个端口都可以在server的端口打开,否则默认使用与前端相同的端口打开
7、stat
listen stats
bind *:3306                        #让stats统计报告监听在1515端口上
stats enable                       #开启stats功能
stats hide-version                 #隐藏版本信息
stats uri /hpadmin?stats           #设置uri
stats realm HAporxy\ admin         #开启认证时登录框显示的信息
stats auth admin:admin             #认证的账号密码
stats admin if TRUE                #如果上面条件认证通过,开启管理接口
stats scope .                      #仅能为127.0.0.1本地访问
stats scope { <name> | "." }
<name>:可以是一个“listen”、“frontend”或“backend”区段的名称,而“.”则表示stats scope语句所定义的当前区段

8、errorfile
errorfile:在用户请求不存在的页面时,返回一个页面文件给客户端,这里可用的状态码有200、400、403、408、500、502、503和504;
errorfile 400 /etc/haproxy/errorpages/400badreq.http
errorfile 403 /etc/haproxy/errorpages/403forbid.http
errorfile 503 /etc/haproxy/errorpages/503sorry.http

9、option forwardfor:允许在发往服务器的请求首部中插入“X-Forwarded-For”首部。
LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined


10、ACL
haproxy的ACL用于实现基于请求报文的首部、响应报文的内容或其它的环境状态信息来做出转发决策,这大大增强了其配置弹性。其配置法则通常分为两步,首先去定义ACL,即定义一个测试条件,而后在条件得到满足时执行某特定的动作,如阻止请求或转发至某特定的后端。定义ACL的语法格式如下。
acl <aclname> <criterion> [flags] [operator] <value> ...
<aclname>:ACL名称,区分字符大小写,且其只能包含大小写字母、数字、-(连接线)、_(下划线)、.(点号)和:(冒号);haproxy中,acl可以重名,这可以把多个测试条件定义为一个共同的acl;
<criterion>:测试标准,即对什么信息发起测试;测试方式可以由[flags]指定的标志进行调整;而有些测试标准也可以需要为其在<value>之前指定一个操作符[operator];
[flags]:目前haproxy的acl支持的标志位有3个:
-i:不区分<value>中模式字符的大小写;
-f:从指定的文件中加载模式;
--:标志符的强制结束标记,在模式中的字符串像标记符时使用;
<value>:acl测试条件支持的值有以下四类:
整数或整数范围:如1024:65535表示从1024至65535;仅支持使用正整数(如果出现类似小数的标识,其为通常为版本测试),且支持使用的操作符有5个,分别为eq、ge、gt、le和lt;
字符串:支持使用“-i”以忽略字符大小写,支持使用“\”进行转义;如果在模式首部出现了-i,可以在其之前使用“--”标志位;
正则表达式:其机制类同字符串匹配;
IP地址及网络地址
同一个acl中可以指定多个测试条件,这些测试条件需要由逻辑操作符指定其关系。条件间的组合测试关系有三种:“与”(默认即为与操作)、“或”(使用“||”操作符)以及“非”(使用“!”操作符)。
1)常用的测试标准(criteria)
be_sess_rate(backend) <integer>
用于测试指定的backend上会话创建的速率(即每秒创建的会话数)是否满足指定的条件;常用于在指定backend上的会话速率过高时将用户请求转发至另外的backend,或用于阻止攻击行为。例如:
backend dynamic
mode http
acl being_scanned be_sess_rate gt 50
redirect location /error_pages/denied.html if being_scanned
fe_sess_rate(frontend) <integer>
用于测试指定的frontend(或当前frontend)上的会话创建速率是否满足指定的条件;常用于为frontend指定一个合理的会话创建速率的上限以防止服务被滥用。例如下面的例子限定入站邮件速率不能大于50封/秒,所有在此指定范围之外的请求都将被延时50毫秒。
frontend mail
bind :25
mode tcp
maxconn 500
acl too_fast fe_sess_rate ge 50
tcp-request inspect-delay 50ms
tcp-request content accept if ! too_fast
tcp-request content accept if WAIT_END
hdr(header) <string>
用于测试请求报文中的所有首部或指定首部是否满足指定的条件;指定首部时,其名称不区分大小写,且在括号“()”中不能有任何多余的空白字符。测试服务器端的响应报文时可以使用shdr()。例如下面的例子用于测试首部Connection的值是否为close。
hdr(Connection) -i close
method <string>

测试HTTP请求报文中使用的方法。

path_beg <string>
用于测试请求的URL是否以<string>指定的模式开头。下面的例子用于测试URL是否以/static、/images、/javascript或/stylesheets头。
acl url_static path_beg -i /static /images /javascript /stylesheets
path_end <string>
用于测试请求的URL是否以<string>指定的模式结尾。例如,下面的例子用户测试URL是否以jpg、gif、png、css或js结尾。
acl url_static path_end -i .jpg .gif .png .css .js
hdr_beg <string>
用于测试请求报文的指定首部的开头部分是否符合<string>指定的模式。例如,下面的例子测试请求是否为提供静态内容的主机img、video、download或ftp。
acl host_static hdr_beg(host) -i img. video. download. ftp.
hdr_end <string>
用于测试请求报文的指定首部的结尾部分是否符合<string>指定的模式
用法一:
将源IP为172.16.253.254的用户禁止、将403的错误重定向到其他服务器;
frontend  webservers
bind *:80
default_backend webservs
acl badguy src 172.16.253.254
block if badguy
errorloc 403 http://www.baidu.com 用法二:
当用户访问地址为172.16.2.1时,将访问页面重定向http://www.baidu.com
frontend  webservers
bind *:80
default_backend webservs
acl dstipaddr hdr(Host) 172.16.2.1
redirect location http://www.baidu.com if dstipaddr
用法三:
acl中path的使用
frontend  webservers
bind *:80
default_backend webservs
acl badguy src 172.16.253.254
acl denyfile path /1.html
http-request deny if badguy denyfile
用法四:
读写分离:
acl  read method GET
acl  read method HEAD
acl write method PUT
acl write method POST
use_backend imgservers if read
use_backend uploadservers if write
用法五:
动静分离
acl static path_end .html
use_backend staticservs if static
default_backend appservs
三、keepalived+haproxy动静分离部署discuz





192.168.1.200配置:
haproxy配置
global
log         127.0.0.1 local2
chroot      /var/lib/haproxy
pidfile     /var/run/haproxy.pid
maxconn     4000
user        haproxy
group       haproxy
daemon
stats socket /var/lib/haproxy/stats
defaults
mode                    http
log                     global
option                  httplog
option                  dontlognull
option http-server-close
option forwardfor       except 127.0.0.0/8
option                  redispatch
retries                 3
timeout http-request    10s
timeout queue           1m
timeout connect         10s
timeout client          1m
timeout server          1m
timeout http-keep-alive 10s
timeout check           10s
maxconn                 3000
frontend main
bind 192.168.1.250:80
acl url_static       path_beg       -i /static /images /javascript /stylesheets
acl url_static       path_end       -i .jpg .gif .png .css .js
use_backend static          if url_static
default_backend             web
backend static
balance     roundrobin
server      static 192.168.1.202:80  check port 80
backend web
balance     roundrobin
server      web 192.168.1.203:80 check port 80
keepalived配置:
! Configuration File for keepalived

global_defs {
notification_email {
root@localhost
}
notification_email_from root
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_10
}
vrrp_script haproxy {
script "/etc/keepalived/haproxy.sh"
interval 1
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.250/24 dev eth0 label eth0:1
}
track_script {
haproxy
}
}
/etc/keepalived/haproxy.sh
#!/bin/bash
counter=$(ps -C haproxy --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg
sleep 2
counter=$(ps -C haproxy --no-heading|wc -l)
if [ "${counter}" = "0" ]; then
/etc/init.d/keepalived stop
fi
fi
192.168.1.201配置类似修改优先级和state
192.168.1.204配置
mysql授权:
mysql> grant all on discuz.* to disuser@'%' identified by 'smile';
mysql> flush privileges;
nfs配置:
vim /etc/exports
/data/discuz *(rw) //discuz访问权限为文件权限和客户及读写权限
chmod -R 777 /data/discuz
192.168.1.203配置:
yum install php php-mysql -y
mkdir /var/www/hrml/discuz
mount -t nfs 192.168.1.204:/data/discuz /var/www/html/discuz
192.168.1.204配置:
mount -t nfs 192.168.1.204:/data/discuz /var/www/html/discuz


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  haproxy