HAProxy介紹
(1)HAProxy 是一款提供高可用性、負載均衡以及基于TCP(第四層)和HTTP(第七層)應用的代理軟體,支援虛拟主機,它是免費、快速并且可靠的一種解決方案。 HAProxy特别适用于那些負載特大的web站點,這些站點通常又需要會話保持或七層處理。HAProxy運作在時下的硬體上,完全可以支援數以萬計的 并發連接配接。并且它的運作模式使得它可以很簡單安全的整合進您目前的架構中, 同時可以保護你的web伺服器不被暴露到網絡上。
(2)HAProxy 實作了一種事件驅動、單一程序模型,此模型支援非常大的并發連接配接數。多程序或多線程模型受記憶體限制 、系統排程器限制以及無處不在的鎖限制,很少能處理數千并發連接配接。事件驅動模型因為在有更好的資源和時間管理的使用者端(User-Space) 實作所有這些任務,是以沒有這些問題。此模型的弊端是,在多核系統上,這些程式通常擴充性較差。這就是為什麼他們必須進行優化以 使每個CPU時間片(Cycle)做更多的工作。
(3)HAProxy 支援連接配接拒絕 : 因為維護一個連接配接的打開的開銷是很低的,有時我們很需要限制攻擊蠕蟲(attack bots),也就是說限制它們的連接配接打開進而限制它們的危害。 這個已經為一個陷于小型DDoS攻擊的網站開發了而且已經拯救了很多站點,這個優點也是其它負載均衡器沒有的。
(4)HAProxy 支援全透明代理(已具備硬體防火牆的典型特點): 可以用用戶端IP位址或者任何其他位址來連接配接後端伺服器. 這個特性僅在Linux 2.4/2.6核心打了cttproxy更新檔後才可以使用. 這個特性也使得為某特殊伺服器處理部分流量同時又不修改伺服器的位址成為可能。
性能,HAProxy借助于OS上幾種常見的技術來實作性能的最大化:
(1)單程序、事件驅動模型顯著降低了上下文切換的開銷及記憶體占用。
(2)O(1)事件檢查器(event checker)允許其在高并發連接配接中對任何連接配接的任何事件實作即時探測。
(3)在任何可用的情況下,單緩沖(single buffering)機制能以不複制任何資料的方式完成讀寫操作,這會節約大量的CPU時鐘周期及記憶體帶寬。
(4)借助于Linux 2.6 (>= 2.6.27.19)上的splice()系統調用,HAProxy可以實作零複制轉發(Zero-copy forwarding),在Linux 3.5及以上的OS中還可以實作零複制啟動(zero-starting)。
(5)記憶體配置設定器在固定大小的記憶體池中可實作即時記憶體配置設定,這能夠顯著減少建立一個會話的時長。
(6)樹型存儲:側重于使用作者多年前開發的彈性二叉樹,實作了以O(log(N))的低開銷來保持計時器指令、保持運作隊列指令及管理輪詢及最少連接配接隊列。
(7)優化的HTTP首部分析:優化的首部分析功能避免了在HTTP首部分析過程中重讀任何記憶體區域。
(8)精心地降低了昂貴的系統調用,大部分工作都在使用者空間完成,如時間讀取、緩沖聚合及檔案描述符的啟用和禁用等。
所有的這些細微之處的優化實作了在中等規模負載之上依然有着相當低的CPU負載,甚至于在非常高的負載場景中,5%的使用者空間占用率和95%的系統空間占用率也是非常普遍的現象,這意味着HAProxy程序消耗比系統空間消耗低20倍以上。是以,對OS進行性能調優是非常重要的。即使使用者空間的占用率提高一倍,其CPU占用率也僅為10%,這也解釋了為何7層處理對性能影響有限這一現象。由此,在高端系統上HAProxy的7層性能可輕易超過硬體負載均衡裝置。
在生産環境中,在7層處理上使用HAProxy作為昂貴的高端硬體負載均衡裝置故障故障時的緊急解決方案也時長可見。硬體負載均衡裝置在“封包”級别處理請求,這在支援跨封包請求(request across multiple packets)有着較高的難度,并且它們不緩沖任何資料,是以有着較長的響應時間。對應地,軟體負載均衡裝置使用TCP緩沖,可建立極長的請求,且有着較大的響應時間。
系統環境centos7.0
[root@bogon ~]# uname -r
3.10.0-327.10.1.el7.x86_64
haproxy 192.168.231.129
apache 192.168.231.128:80
apache 192.168.231.130:80/8080
軟體haproxy+apache做負載均衡
[[email protected]]$ apache(httpd-2.2.26)
[[email protected]]$ tar –zxvf httpd-2.2.26.tar.gz
[[email protected]]$ cd httpd-2.2.26
[[email protected]]$./configure --prefix=/usr/local/apache
--with-apr=/usr/local/apr-httpd/
--with-apr-util=/usr/local/apr-util-httpd/ --enable-so
--enable-mods-shared=all --with-mpm=worker
[[email protected]]$ make && make install
[[email protected]]$ ln -s /usr/local/apache/bin/* /usr/local/bin
[[email protected]]$ /usr/local/apache/bin/apachectl start
[[email protected]]$cat /etc/init.d/httpd

#!/bin/bash
#
# Startup script for the Apache Web Server
#
# chkconfig: - 85 15
# description: Apache is a World Wide Web server. It is used to serve \
# HTML files and CGI.
# processname: httpd
# pidfile: /usr/local/apache/logs/httpd.pid
# config: /usr/local/apache/conf/httpd.conf
# Source function library.
. /etc/rc.d/init.d/functions
if [ -f /etc/sysconfig/httpd ]; then
. /etc/sysconfig/httpd
fi
# This will prevent initlog from swallowing up a pass-phrase prompt if
# mod_ssl needs a pass-phrase from the user.
INITLOG_ARGS=""
# Path to the apachectl script, server binary, and short-form for messages.
apachectl=/usr/local/apache/bin/apachectl
httpd=/usr/local/apache/bin/httpd
pid=/usr/local/apache/logs/httpd.pid
prog=httpd
RETVAL=0
# The semantics of these two functions differ from the way apachectl does
# things -- attempting to start while running is a failure, and shutdown
# when not running is also a failure. So we just do it the way init scripts
# are expected to behave here.
start() {
echo -n $"Starting $prog: "
daemon $httpd $OPTIONS
RETVAL=$?
echo
[ $RETVAL = 0 ] && touch /var/lock/subsys/httpd
return $RETVAL
}
stop() {
echo -n $"Stopping $prog: "
killproc $httpd
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f /var/lock/subsys/httpd $pid
}
reload() {
echo -n $"Reloading $prog: "
killproc $httpd -HUP
RETVAL=$?
echo
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status $httpd
RETVAL=$?
;;
restart)
stop
start
;;
condrestart)
if [ -f $pid ] ; then
stop
start
fi
;;
reload)
reload
;;
graceful|help|configtest|fullstatus)
$apachectl $@
RETVAL=$?
;;
*)
echo $"Usage: $prog {start|stop|restart|condrestart|reload|status"
echo $"|fullstatus|graceful|help|configtest}"
exit 1
esac
exit $RETVAL
啟動腳本
[[email protected]]$ chmod 755 /etc/init.d/httpd
[[email protected]]$ chkconfig –add httpd
[[email protected]]$ chkconfig --level 345 httpd on
做域名的虛拟伺服器
[[email protected]]$ cat /usr/local/http/confhttpd.conf
1 ServerName 192.168.231.130:80
2
3 Include conf/vhost/*.conf
[[email protected]]$ cat /usr/local/apacache2/conf/vhost/accp.conf
1 NameVirtualHost *:8080
2 <VirtualHost *:8080>
3 DocumentRoot "/usr/local/apacache2/htdocs/accp"
4 ServerName www.accp.com
5 ErrorLog "logs/accp.err.log"
6 CustomLog "logs/accp.acc.log" common
7 </VirtualHost>
[[email protected]]$tar -zxvf haproxy-1.49.tar.gz
[[email protected]]$ cd haproxy-1.4.9
[[email protected]]$make TARGET=linux26 PREFIX=/haproxy
[[email protected]]$ make install PREFIX=/haproxy
[[email protected]]$mkdir /home/haproxy/logs/
[[email protected]]$mkdir /etc/haproxy/
[root@haproxy]$cat haproxy.conf

global
log 127.0.0.1 local3
#log 127.0.0.1 local1 notice
#log loghost local0 info
maxconn 4096
#chroot /usr/local/haproxy
#chroot /home/haproxy
uid 502
gid 502
daemon
nbproc 1
pidfile /home/haproxy/logs/haproxy.pid
#debug
#quiet
defaults
log global
mode http
option httplog
option dontlognull
option forwardfor
option redispatch
log 127.0.0.1 local3
retries 3
maxconn 32000
balance roundrobin
stats uri /haproxy-stats
contimeout 5000
clitimeout 50000
srvtimeout 50000
listen web_proxy *:80
appsession JSESSIONID len 52 timeout 3h
#插入cookie的方式
cookie SRV insert indirect nocache
#模式有http tcp health
mode http
stats enable
stats hide-version
#檢視狀态
stats uri /haproxy-stats
stats refresh 10s
monitor-uri /haproxy_test
#負載均衡方案:輪調
balance roundrobin
option httpclose
#後端可以擷取用戶端的真實ip
option forwardfor
#健康檢查
option httpchk HEAD /login HTTP/1.0
#option httpchk GET /ping.jsp
#後端真實服務
server webA 192.168.231.128:80 cookie A check
server webB 192.168.231.130:8080 cookie B check
server webB 192.168.231.130:8080 cookie B check
backend web
mode http
balance roundrobin
cookie SEESSION_COOKIE insert indirect nocache
server web1 192.168.231.129:8080 #cookie 11 check inter 1500 rise 3 fall 3 weight 1
server web2 192.168.231.128:80 cookie 11 check inter 1500 rise 3 fall 3 weight 1
server web3 192.168.231.129:8090 cookie 11 check inter 1500 rise 3 fall 3 weight 1
frontend webs
bind 0.0.0.0:83
default_backend web
haproxy.conf

####################全局配置資訊########################
#######參數是程序級的,通常和作業系統(OS)相關#########
global
maxconn 20480 #預設最大連接配接數
log 127.0.0.1 local3 #[err warning info debug]
chroot /var/haproxy #chroot運作的路徑
uid 99 #所屬運作的使用者uid
gid 99 #所屬運作的使用者組
daemon #以背景形式運作haproxy
nbproc 1 #程序數量(可以設定多個程序提高性能)
pidfile /var/run/haproxy.pid #haproxy的pid存放路徑,啟動程序的使用者必須有權限通路此檔案
ulimit-n 65535 #ulimit的數量限制
#####################預設的全局設定######################
##這些參數可以被利用配置到frontend,backend,listen元件##
defaults
log global
mode http #所處理的類别 (#7層 http;4層tcp )
maxconn 20480 #最大連接配接數
option httplog #日志類别http日志格式
option httpclose #每次請求完畢後主動關閉http通道
option dontlognull #不記錄健康檢查的日志資訊
option forwardfor #如果後端伺服器需要獲得用戶端真實ip需要配置的參數,可以從Http Header中獲得用戶端ip
option redispatch #serverId對應的伺服器挂掉後,強制定向到其他健康的伺服器
option abortonclose #當伺服器負載很高的時候,自動結束掉目前隊列處理比較久的連接配接
stats refresh 30 #統計頁面重新整理間隔
retries 3 #3次連接配接失敗就認為服務不可用,也可以通過後面設定
balance roundrobin #預設的負載均衡的方式,輪詢方式
#balance source #預設的負載均衡的方式,類似Nginx的ip_hash
#balance leastconn #預設的負載均衡的方式,最小連接配接
contimeout 5000 #連接配接逾時
clitimeout 50000 #用戶端逾時
srvtimeout 50000 #伺服器逾時
timeout check 2000 #心跳檢測逾時
####################監控頁面的設定#######################
listen admin_status #Frontend和Backend的組合體,監控組的名稱,按需自定義名稱
bind 0.0.0.0:65532 #監聽端口
mode http #http的7層模式
log 127.0.0.1 local3 err #錯誤日志記錄
stats refresh 5s #每隔5秒自動重新整理監控頁面
stats uri /admin?stats #監控頁面的url
stats realm itnihao itnihao #監控頁面的提示資訊
stats auth admin:admin #監控頁面的使用者和密碼admin,可以設定多個使用者名
stats auth admin1:admin1 #監控頁面的使用者和密碼admin1
stats hide-version #隐藏統計頁面上的HAproxy版本資訊
stats admin if TRUE #手工啟用/禁用,後端伺服器(haproxy-1.4.9以後版本)
errorfile 403 /etc/haproxy/errorfiles/403.http
errorfile 500 /etc/haproxy/errorfiles/500.http
errorfile 502 /etc/haproxy/errorfiles/502.http
errorfile 503 /etc/haproxy/errorfiles/503.http
errorfile 504 /etc/haproxy/errorfiles/504.http
#################HAProxy的日志記錄内容設定###################
capture request header host len 40
capture request header Content-Length len 10
capture request header Referer len 200
capture response header Server len 40
capture response header Content-Length len 10
capture response header Cache-Control len 8
#######################網站監測listen配置#####################
###########此用法主要是監控haproxy後端伺服器的監控狀态############
listen site_status
bind 0.0.0.0:1081 #監聽端口
mode http #http的7層模式
log 127.0.0.1 local3 err #[err warning info debug]
monitor-uri /site_status #網站健康檢測URL,用來檢測HAProxy管理的網站是否可以用,正常傳回200,不正常傳回503
acl site_dead nbsrv(server_web) lt 2 #定義網站down時的政策當挂在負載均衡上的指定backend的中有效機器數小于1台時傳回true
acl site_dead nbsrv(server_blog) lt 2
acl site_dead nbsrv(server_bbs) lt 2
monitor fail if site_dead #當滿足政策的時候傳回503,網上文檔說的是500,實際測試為503
monitor-net 192.168.16.2/32 #來自192.168.16.2的日志資訊不會被記錄和轉發
monitor-net 192.168.16.3/32
########frontend配置############
#####注意,frontend配置裡面可以定義多個acl進行比對操作########
frontend http_80_in
bind 0.0.0.0:80 #監聽端口,即haproxy提供web服務的端口,和lvs的vip端口類似
mode http #http的7層模式
log global #應用全局的日志配置
option httplog #啟用http的log
option httpclose #每次請求完畢後主動關閉http通道,HA-Proxy不支援keep-alive模式
option forwardfor #如果後端伺服器需要獲得用戶端的真實IP需要配置次參數,将可以從Http Header中獲得用戶端IP
########acl政策配置#############
acl itnihao_web hdr_reg(host) -i ^(www.itnihao.cn|ww1.itnihao.cn)$
#如果請求的域名滿足正規表達式中的2個域名傳回true -i是忽略大小寫
acl itnihao_blog hdr_dom(host) -i blog.itnihao.cn
#如果請求的域名滿足www.itnihao.cn傳回true -i是忽略大小寫
#acl itnihao hdr(host) -i itnihao.cn
#如果請求的域名滿足itnihao.cn傳回true -i是忽略大小寫
#acl file_req url_sub -i killall=
#在請求url中包含killall=,則此控制政策傳回true,否則為false
#acl dir_req url_dir -i allow
#在請求url中存在allow作為部分位址路徑,則此控制政策傳回true,否則傳回false
#acl missing_cl hdr_cnt(Content-length) eq 0
#當請求的header中Content-length等于0時傳回true
########acl政策比對相應#############
#block if missing_cl
#當請求中header中Content-length等于0阻止請求傳回403
#block if !file_req || dir_req
#block表示阻止請求,傳回403錯誤,目前表示如果不滿足政策file_req,或者滿足政策dir_req,則阻止請求
use_backend server_web if itnihao_web
#當滿足itnihao_web的政策時使用server_web的backend
use_backend server_blog if itnihao_blog
#當滿足itnihao_blog的政策時使用server_blog的backend
#redirect prefix http://blog.itniaho.cn code 301 if itnihao
#當通路itnihao.cn的時候,用http的301挑轉到http://192.168.16.3
default_backend server_bbs
#以上都不滿足的時候使用預設server_bbs的backend
##########backend的設定##############
#下面我将設定三組伺服器 server_web,server_blog,server_bbs
###########################backend server_web#############################
backend server_web
mode http #http的7層模式
balance roundrobin #負載均衡的方式,roundrobin平均方式
cookie SERVERID #允許插入serverid到cookie中,serverid後面可以定義
option httpchk GET /index.html #心跳檢測的檔案
server web1 192.168.16.2:80 cookie web1 check inter 1500 rise 3 fall 3 weight 1
#伺服器定義,cookie 1表示serverid為web1,check inter 1500是檢測心跳頻率rise 3是3次正确認為伺服器可用,
#fall 3是3次失敗認為伺服器不可用,weight代表權重
server web2 192.168.16.3:80 cookie web2 check inter 1500 rise 3 fall 3 weight 2
#伺服器定義,cookie 1表示serverid為web2,check inter 1500是檢測心跳頻率rise 3是3次正确認為伺服器可用,
#fall 3是3次失敗認為伺服器不可用,weight代表權重
##################################backend server_blog###############################################
backend server_blog
mode http #http的7層模式
balance roundrobin #負載均衡的方式,roundrobin平均方式
cookie SERVERID #允許插入serverid到cookie中,serverid後面可以定義
option httpchk GET /index.html #心跳檢測的檔案
server blog1 192.168.16.2:80 cookie blog1 check inter 1500 rise 3 fall 3 weight 1
#伺服器定義,cookie 1表示serverid為web1,check inter 1500是檢測心跳頻率rise 3是3次正确認為伺服器可用,fall 3是3次失敗認為伺服器不可用,weight代表權重
server blog2 192.168.16.3:80 cookie blog2 check inter 1500 rise 3 fall 3 weight 2
#伺服器定義,cookie 1表示serverid為web2,check inter 1500是檢測心跳頻率rise 3是3次正确認為伺服器可用,fall 3是3次失敗認為伺服器不可用,weight代表權重
##################################backend server_bbs###############################################
backend server_bbs
mode http #http的7層模式
balance roundrobin #負載均衡的方式,roundrobin平均方式
cookie SERVERID #允許插入serverid到cookie中,serverid後面可以定義
option httpchk GET /index.html #心跳檢測的檔案
server bbs1 192.168.16.2:80 cookie bbs1 check inter 1500 rise 3 fall 3 weight 1
#伺服器定義,cookie 1表示serverid為web1,check inter 1500是檢測心跳頻率rise 3是3次正确認為伺服器可用,fall 3是3次失敗認為伺服器不可用,weight代表權重
server bbs2 192.168.16.3:80 cookie bbs2 check inter 1500 rise 3 fall 3 weight 2
#伺服器定義,cookie 1表示serverid為web2,check inter 1500是檢測心跳頻率rise 3是3次正确認為伺服器可用,fall 3是3次失敗認為伺服器不可用,weight代表權重
[root@haproxy]$ haparoxy -f haproxy.conf 檢查配置檔案
測試haproxy監控
http://192.168.231.129:81/haproxy-stats
測試網站代理
http://192.168.231.129:83