os:

[root@node1 ~]# cat /etc/system-release

CentOS release 6.4 (Final)

参考文章:http://www.serverlab.ca/tutorials/linux/network-services/deploying-an-haproxy-load-balancer-on-centos-6/

安装epel源:

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

rpm -ivh epel-release-6.8.noarch.rpm

yum install haproxy -y

  tcp mode:

wKioL1e5WgySfqWrAAAhQROUPx8034.png

 http mode

wKiom1e5XOGxNbKiAAAnVUdFhPw068.png

配置文件说明:

1、代理

    -defaults:用于为所有其他配置提供默认参数,这配置默认配置参数可由下一个“defaults”所重新设定

    -frontend:用于定义一系列监听的套接字,这些套接字可接受客户端请求并与之建立连接

    -backend:用于定义一系列后端服务器,代理将会将对应客户端的请求转发至这些服务器

    -listen:把一个前端和一个后端绑在一起,通过关联前端和后端定义了一个完整的代理,通常只对tcp流量有用

    所有代理的名称只能使用大写字母、小写字母、数字、-、_、点号、冒号,此外ACL名称会区分字母大小写


balance定义负载均衡算法,可用于defaults、listen、backend

    roundrobin:基于权重进行轮叫,动态

    static-rr:基于权重进行轮叫,静态

    source:类似于nginx中的ip_hash,默认为静态

    uri:问号之前的左半部分uri,同一个uri请求对应同一个后端服务器,此算法常用于代理缓存或反病毒代理,以提高缓存的命中率,默认为静态

    leastconn新的连接请求被派发至具有最少连接数目的后端服务器,在有着较长时间会话的场景中推荐使用此算法,如LDAP、SQL等,其并不太适合用于较短会话的应用层协议,如http,此算法是动态的,可以在运行时调整其权重


官方给出的一个简单实例配置:

global
        daemon
        maxconn 256    -》haproxy负载均衡服务器最大连接数

    defaults
        mode http    -》定义模式http或者tcp或者health
        timeout connect 5000ms     -》连接超时时长
        timeout client 50000ms     -》客户端请求超时时长
        timeout server 50000ms     -》服务器响应超时时长

    frontend http-in    -》frontend定义前端名称
        bind *:80       -》haproxy绑定的ip与端口
        default_backend servers   ->默认后端服务器

    backend servers   -》backend定义后端服务器
        server server1 127.0.0.1:8000 maxconn 32  -》server关键字,server1为后端服务器名称

利用下面命令查看配置文件是否有错:

测试:192.168.1.155

将haproxy和nginx服务放置在一起,nginx采用8080端口,haproxy80端口,简单配置,浏览器访问

http://192.168.1.155

wKioL1e5Xxexfp16AABNrlepuCE044.jpg

定义stats:统计数据的设置情况

stats:统计数据的设置状况

    stats enable

    stats hide-version:隐藏版本

    stats uri /haproxy?stats:uri也可以自己定义

    stats realm "haproxy statistics":认证提示信息

    stats auth "admin:admin"--->认证,账号和密码(auth可以用多次)

    stats scope no restriction

    stats refresh 5s:刷新时长

    stats admin {if|unless} <cond>

    stats admin if true:如果认证通过就能管理节点server

    例:listen statistics

bind *:8009:单独定义,使用新的端口,为了安全

stats enable:启用stats

        stats hide-version:隐藏版本

        stats uri /haproxy?stats

        stats realm "haproxy statistics"

stats auth admin:admin    --->认证,账号和密码(auth可以用多次)

        stats scope no restriction

        stats refresh 5s:刷新时长

参考:http://cbonte.github.io/haproxy-dconv/configuration-1.5.html#4-stats%20auth

状态图:

wKiom1e5ZMzyHhudAADIEkaNFtw521.jpg启用haproxy日志记录:

vim /etc/rsyslog.conf

# Provides UDP syslog reception

$ModLoad imudp

$UDPServerRun 514


# Provides TCP syslog reception

$ModLoad imtcp

$InputTCPServerRun 514

将以上udp,tcp支持打开,然后在加入下一行

local2.*/var/log/haproxy.log

最后重启服务

service rsyslog restart

haproxy配置文件默认日志在global下面

log         127.0.0.1 local2


monitor-uri <uri>:拦截一个URI所使用的外部组件的监控要求

Use /haproxy_test to report haproxy's status

defaults

    mode http

    timeout connect 5s

    timeout client 50s

    timeout server 50s

    option forwardfor except 127.0.0.1

    monitor-uri /haproxy_test    ------》报告haproxy的状态

效果如图:

wKiom1e5biODElpjAAA7vRis8sg688.jpg

option forwardfor

Enable insertion of the X-Forwarded-For header to requests sent to servers
效果如下:
192.168.1.155 - - [17/Aug/2016:10:18:35 +0800] "GET / HTTP/1.1" 200 16 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0" "192.168.1.109"
192.168.1.155 - - [17/Aug/2016:10:19:09 +0800] "GET / HTTP/1.1" 200 16 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0" "-"
添加了这个选项网站日志会记录客户端的ip也就是192.168.1.109
常用为:option forwardfor except 127.0.0.1

option httplog:记录http记录,和option logasap一起使用更好
效果如下:
不使用前:
[root@node1 html]# cat /var/log/haproxy.log 
Aug 21 11:12:36 localhost haproxy[6711]: Proxy statistics started.
Aug 21 11:12:36 localhost haproxy[6711]: Proxy http-in started.
Aug 21 11:12:36 localhost haproxy[6711]: Proxy servers started.
Aug 21 11:12:38 localhost haproxy[6712]: Connect from 192.168.1.109:10276 to 192.168.1.155:80 (http-in/HTTP)
Aug 21 11:12:39 localhost haproxy[6712]: Connect from 192.168.1.109:10277 to 192.168.1.155:80 (http-in/HTTP)
使用后:
Aug 21 11:15:24 localhost haproxy[6755]: Proxy http-in started.
Aug 21 11:15:24 localhost haproxy[6755]: Proxy servers started.
Aug 21 11:15:27 localhost haproxy[6756]: 192.168.1.109:10287 [21/Aug/2016:11:15:27.478] http-in servers/server1 5/0/1/0/6 304 158 - - ---- 1/1/0/1/0 0/0 "GET / HTTP/1.1"
Aug 21 11:15:27 localhost haproxy[6756]: 192.168.1.109:10287 [21/Aug/2016:11:15:27.485] http-in servers/server2 468/0/2/1/471 200 231 - - ---- 1/1/0/1/0 0/0 "GET / HTTP/1.1"
Aug 21 11:15:28 localhost haproxy[6756]: 192.168.1.109:10287 [21/Aug/2016:11:15:27.956] http-in servers/server1 429/0/1/1/431 200 240 - - ---- 1/1/0/1/0 0/0 "GET / HTTP/1.1"
可以清楚的看出客户端请求后端服务器的的详细过程

option   redispatch# 当使用了cookie时,haproxy将会将其请求的后端服务器的serverID插入到cookie中,以保证会话的SESSION持久性;而此时,如果后端的服务器宕掉了, 但是客户端的cookie是不会刷新的,如果设置此参数,将会将客户的请求强制定向到另外一个后端server上,以保证服务的正常。

retries    3# 定义连接后端服务器的失败重连次数,连接失败次数超过此值后将会将对应后端

自定义错误页面
    errorfile <code> file:200 403 408 500 502 503 504 400
    errorfile 400 /etc/haproxy/XXX.http:给出定义错误页面
    
ACL:访问控制列表
    acl <aclname> <criterrion> [flags][operator]<value>区分字符大小写
    flags:
	-i:不区分字符大小
    path_beg <string>:path路径以某字符串开始
    path_end <string>:path路径以什么结尾(文件名扩展名都可以)
    path_reg <regex>:支持正则
    url <string>:整个后面的路径
    method <string> 
    acl url_static path_beg /static /p_w_picpaths /img /css:定义以/p_w_picpaths /img /css为开头的url
    acl url_static path_end -i .gif .png .jpg .css .js:定义以它们结尾,不区分大小写
    acl host_www hdr_beg(host) -i www  :hdr_reg(header) <regex>:对首部host进行正则表达式
    use_backend static if url_static  :如果满足url_static控制列表定义的使用后端static组
    use_backend www if host_www   :如果满足host_www控制列表定义的使用后端www组
    default_backend web    :其他没有满足的使用web后端组
    
对后端upstream server进行动静分离:
    frontend webserver
    bind *:80
    acl url_static		path_beg		-i /static /p_w_picpaths /javascript /stylesheets
    acl url_static		path_end		-i .gif .png .jpg .jpeg .js .html
    acl url_dynamic		path_end		-i .php
    use_backend static		if url_static or host_static
    use_backend dynamic		if url_dynamic
    default_backend		dynamic
    
backend static
    server node1 192.168.1.155:80 check maxconn 2000
				
backend dynamic
    server node2 192.168.1.11:80 check maxconn 2000
看效果图:默认后端为动态

wKiom1e5kRGT5NS4AACrCB8nlz4792.jpg

带有index.html为静态

wKioL1e5kS_Rv7QgAABA285QvsM614.jpg


option      dontlognull   --》启用该项,日志中将不会记录空连接。所谓空连接就是在上游的负载均衡器或者监控系统为了探测该 服务是否存活可用时,需要定期的连接或者获取某一固定的组件或页面,或者探测扫描端口是否在监听或开放等动作被称为空连接;官方文档中标注,如果该服务上游没有其他的负载均衡器的话,建议不要使用该参数,因为互联网上的恶意扫描或其他动作就不会被记录下来


附带线上配置文件:

global

    log         127.0.0.1 local2

    chroot      /var/lib/haproxy

    pidfile     /var/run/haproxy.pid

    maxconn     4000

    user        haproxy

    group       haproxy

    daemon


defaults

    mode                    http

    log                     global

    option                  httplog

    option                  dontlognull

    option http-server-close    ---》server启动关闭功能

    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                 30000


listen stats

    mode http

    bind *:1080

    stats enable

    stats hide-version

    stats uri     /haproxyadmin?stats

    stats realm   Haproxy\ Statistics

    stats auth    admin:admin

    stats admin if TRUE


frontend http-in

    bind *:80

    mode http

    log global

    option httpclose      这个选项已经被废弃了,改用http-server-close代替

    option logasap      ---》提前记录日志(接收到http请求就开始记录日志)

    option dontlognull  ---》对空连接不记录日志

    capture request  header Host len 20    ----》记录首部为host的20个字节的记录

    capture request  header Referer len 60   ----》跳转---》防盗链

    default_backend servers


frontend healthcheck

    bind 192.168.1.155:1099

    mode http

    option http-server-close

    option forwardfor

    default_backend servers


backend servers

  balance roundrobin

    server websrv1 192.168.10.11:80 check maxconn 2000

    server websrv2 192.168.10.12:80 check maxconn 2000


配置mysql的负载均衡:

global

    log         127.0.0.1 local2

    chroot      /var/lib/haproxy

    pidfile     /var/run/haproxy.pid

    maxconn     4000

    user        haproxy

    group       haproxy

    daemon


defaults

    mode                    tcp

    log                     global

    option                  httplog

    option                  dontlognull

    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                 600


listen stats

    mode http

    bind 0.0.0.0:1080

    stats enable

    stats hide-version

    stats uri     /haproxyadmin?stats

    stats realm   Haproxy\ Statistics

    stats auth    admin:admin

    stats admin if TRUE


frontend mysql

    bind *:3306

    mode tcp

    log global

    default_backend mysqlservers


backend mysqlservers

    balance leastconn                 ---》(mysql选择此算法)

    server dbsrv1 192.168.10.11:3306 check port 3306 intval 2 rise 1 fall 2 maxconn 300

    server dbsrv2 192.168.10.12:3306 check port 3306 intval 2 rise 1 fall 2 maxconn 300

更多信息,参考官网:http://cbonte.github.io/haproxy-dconv/configuration-1.5.html#option%20httpclose