Haproxy

1、HAProxy的核心功能

  • 負載均衡:L4和L7兩種模式,支持RR/靜態RR/LC/IP Hash/URI Hash/URL_PARAM Hash/HTTP_HEADER Hash等豐富的負載均衡算法
  • 健康檢查:支持TCP和HTTP兩種健康檢查模式
  • 會話保持:對於未實現會話共享的應用集羣,可經過Insert Cookie/Rewrite Cookie/Prefix Cookie,以及上述的多種Hash方式實現會話保持
  • SSL:HAProxy能夠解析HTTPS協議,並可以將請求解密爲HTTP後向後端傳輸
  • HTTP請求重寫與重定向
  • 監控與統計:HAProxy提供了基於Web的統計信息頁面,展示健康狀態和流量數據。基於此功能,使用者能夠開發監控程序來監控HAProxy的狀態

2、HAProxy的關鍵特性

性能html

  • 採用單線程、事件驅動、非阻塞模型,減小上下文切換的消耗,能在1ms內處理數百個請求。而且每一個會話只佔用數KB的內存。
  • 大量精細的性能優化,如O(1)複雜度的事件檢查器、延遲更新技術、Single-buffereing、Zero-copy forwarding等等,這些技術使得HAProxy在中等負載下只佔用極低的CPU資源。
  • HAProxy大量利用操做系統自己的功能特性,使得其在處理請求時能發揮極高的性能,一般狀況下,HAProxy自身只佔用15%的處理時間,剩餘的85%都是在系統內核層完成的。
  • HAProxy做者在8年前(2009)年使用1.4版本進行了一次測試,單個HAProxy進程的處理能力突破了10萬請求/秒,並輕鬆佔滿了10Gbps的網絡帶寬。

穩定性node

做爲建議以單進程模式運行的程序,HAProxy對穩定性的要求是十分嚴苛的。按照做者的說法,HAProxy在13年間從未出現過一個會致使其崩潰的BUG,HAProxy一旦成功啓動,除非操做系統或硬件故障,不然就不會崩潰(我以爲可能多少仍是有誇大的成分)。linux

在上文中提到過,HAProxy的大部分工做都是在操做系統內核完成的,因此HAProxy的穩定性主要依賴於操做系統,做者建議使用2.6或3.x的Linux內核,對sysctls參數進行精細的優化,而且確保主機有足夠的內存。這樣HAProxy就可以持續滿負載穩定運行數年之久。git

 

3、HAProxy、LVS、Nginx三者區別

 

4、HAProxy的安裝和運行

 4.1)下載解壓(官網須要FQ,例以下haproxy-1.5.19.tar.gz)github

wget http://www.haproxy.org/download/1.7/src/haproxy-1.7.2.tar.gz
tar -xzf haproxy-1.7.2.tar.gz

4.2)編譯並安裝web

make PREFIX=/usr/local/haproxy TARGET=linux2628
make install PREFIX=/usr/local/haproxy

PREFIX爲指定的安裝路徑,TARGET則根據當前操做系統內核版本指定:redis

- linux22     for Linux 2.2
- linux24     for Linux 2.4 and above (default)
- linux24e    for Linux 2.4 with support for a working epoll (> 0.21)
- linux26     for Linux 2.6 and above
- linux2628   for Linux 2.6.28, 3.x, and above (enables splice and tproxy)

4.3)建立HAProxy配置文件,由於編譯安裝的配置文件是不生成的,須要去源碼包裏去複製。算法

mkdir -p /usr/local/haproxy/conf
cd /usr/local/haproxy/conf
cp /usr/local/src/haproxy-1.5.19/examples/haproxy.cfg .
vim haproxy.cfg

 

到此安裝結束。vim

5、配置文件

此處對於配置文件不會過多闡述。。後端

# this config needs haproxy-1.1.28 or haproxy-1.2.1

global
	log 127.0.0.1	local0 info
	log 127.0.0.1	local1 warning
	#log loghost	local0 info
	maxconn 4096
	chroot /usr/local/haproxy
	pidfile /usr/local/haproxy/conf/haproxy.pid
	uid 99
	gid 99
	daemon
	#debug
	#quiet
	stats socket /var/run/haproxy.sock mode 600 level admin
        stats timeout 2m

defaults
	log	global
	mode	http
	option	http-keep-alive
	#option	httplog
	#option	dontlognull
	#retries	3
	#redispatch
	maxconn	2000
	#contimeout	5000
	#clitimeout	50000
	#srvtimeout	50000
	timeout connect 5000ms  #??server???5s
	timeout client 50000ms  #???????50s
	timeout server 50000ms  #server?????50s

listen stats
	mode http
	bind *:8888
	stats enable
	stats uri	/haproxy-status
	stats auth	haproxy:haproxy

frontend frontend_www_example_com
	bind *:80
	mode http
	#option httplog
	#log	global
	default_backend backend_www_example_com

backend backend_www_example_com
	option forwardfor header X-REAL-IP
	option httpchk HEAD / HTTP/1.0
	balance source
	server web-node1 192.168.222.147:8080 check source 192.168.222.140:1025-65000 inter 2000 rise 30 fall 15

  

能夠參考以下連接,例如ACL策略,正則匹配策略,session保持,健康檢查,四層與七層負載均衡:

一、HAProxy從零開始到掌握

二、官方文檔

 

6、日誌添加

6.1)修改haproxy.cfg,在global域和defaults域中添加:

global
    ...
    log 127.0.0.1 local0 info
    log 127.0.0.1 local1 warning
    ...

defaults
    ...
    log global
    ...

意思是將info級(及以上)的日誌推送到rsyslog的local0接口,將warn級(及以上)的日誌推送到rsyslog的local1接口,而且全部frontend都默認使用global中的日誌配置。

注:info級的日誌會打印HAProxy處理的每一條請求,會佔用很大的磁盤空間,在生產環境中,建議將日誌級別調整爲notice

6.2)爲rsyslog添加haproxy日誌的配置
vim /etc/rsyslog.conf
# Provides UDP syslog reception   默認是UDP
$ModLoad imudp
$UDPServerRun 514
.
.
.
local0.*                                                /var/log/haproxy/info.log
local1.*                                                /var/log/haproxy/warning.log

6.3)修改rsyslog的啓動參數

vim /etc/sysconfig/rsyslog
# Options for rsyslogd
# Syslogd options are deprecated since rsyslog v3.
# If you want to use them, switch to compatibility mode 2 by "-c 2"
# See rsyslogd(8) for more details
SYSLOGD_OPTIONS="-c 2 -r -m 0"

6.4)重啓rsyslog和HAProxy

service rsyslog restart
service haproxy restart

 

其他沒有什麼好寫的了,具體用的時候仍是看文檔和上面提供的連接吧。  

7、幾個注意點

7.1)有些內核參數的配置可能致使haproxy沒法啓動,例如:

Starting proxy linuxyw.com: cannot bind socket

net.ipv4.ip_nonlocal_bind=1
net.ipv4.ip_forward = 1
配置生效
sysctl –p

7.2)長鏈接,若是不支持長鏈接會產生大量的timewait,tcp端口會被佔滿,,要設置timewait時間  

	縮短time_wait時間
	[root@master conf]# cat /proc/sys/net/ipv4/tcp_fin_timeout 能夠設小爲30,也不要過小
	60
	[root@master conf]# cat /proc/sys/net/ipv4/tcp_tw_recycle 設爲1
	0
	[root@master conf]# cat /proc/sys/net/ipv4/tcp_tw_reuse 設爲1
	0
	[root@master conf]# cat /proc/sys/net/ipv4/ip_local_port_range 改本地的端口範圍
	32768	61000

7.3)端口只有0-65535,當超過這個端口後的解決方法,反向代理的請求方式,客戶端向VIP請求,haproxy再去訪問rs,當請求到了haproxy時能夠將源ip綁定,一個ip對應0-65535個端口 

一、添加一個IP
ifconfig eth0:1 192.168.222.140
二、在haproxy.cfg裏面backend裏添加source
server web-node1 192.168.222.147:8080 check source 192.168.222.140:1025-65000 inter 2000 rise 30 fall 15
三、而後此時在就看到是140發起的請求。
netstat -na | grep 192.168.222.140

 

8、經過unix socket command在線修改haproxy配置不重啓haproxy 

參考

用法:

一、global
        stats socket /var/run/haproxy.sock mode 600 level admin
        stats timeout 2m

二、echo "help" | socat stdio /var/run/haproxy.sock

三、使用
echo "show info" | socat stdio /var/run/haproxy.sock		
echo "show stat" | socat stdio /var/run/haproxy.sock	比較適合作監控
四、關閉某個backend下的某臺server,,下線
echo "disable server backend_www_example_com/web-node2" | socat stdio /var/run/haproxy.sock
[root@master conf]# echo "help" | socat stdio /var/run/haproxy.sock 
Unknown command. Please enter one of the following commands only :
  clear counters : clear max statistics counters (add 'all' for all counters)
  clear table    : remove an entry from a table
  help           : this message
  prompt         : toggle interactive mode with prompt
  quit           : disconnect
  show info      : report information about the running process
  show pools     : report information about the memory pools usage
  show stat      : report counters for each proxy and server
  show errors    : report last request and response errors for each proxy
  show sess [id] : report the list of current sessions or dump this session
  show table [id]: report table usage stats or dump this table's contents
  get weight     : report a server's current weight
  set weight     : change a server's weight
  set server     : change a server's state or weight
  set table [id] : update or create a table entry's data
  set timeout    : change a timeout setting
  set maxconn    : change a maxconn setting
  set rate-limit : change a rate limiting value
  disable        : put a server or frontend in maintenance mode
  enable         : re-enable a server or frontend which is in maintenance mode
  shutdown       : kill a session or a frontend (eg:to release listening ports)
  show acl [id]  : report available acls or dump an acl's contents
  get acl        : reports the patterns matching a sample for an ACL
  add acl        : add acl entry
  del acl        : delete acl entry
  clear acl <id> : clear the content of this acl
  show map [id]  : report available maps or dump a map's contents
  get map        : reports the keys and values matching a sample for a map
  set map        : modify map entry
  add map        : add map entry
  del map        : delete map entry
  clear map <id> : clear the content of this map
  set ssl <stmt> : set statement for ssl

  
[root@master conf]# echo "show info" | socat stdio /var/run/haproxy.sock 
Name: HAProxy
Version: 1.5.19
Release_date: 2016/12/25
Nbproc: 1
Process_num: 1
Pid: 14091
Uptime: 0d 0h02m26s
Uptime_sec: 146
Memmax_MB: 0
Ulimit-n: 8225
Maxsock: 8225
Maxconn: 4096
Hard_maxconn: 4096
CurrConns: 0
CumConns: 2
CumReq: 2
Maxpipes: 0
PipesUsed: 0
PipesFree: 0
ConnRate: 0
ConnRateLimit: 0
MaxConnRate: 0
SessRate: 0
SessRateLimit: 0
MaxSessRate: 0
CompressBpsIn: 0
CompressBpsOut: 0
CompressBpsRateLim: 0
Tasks: 7
Run_queue: 1
Idle_pct: 100
node: master
description: 

  

9、證實HAProxy是反向代理

從一臺機器請求一個頁面的返回結果:
一、請求一個頭,這個IP是HAPROXY的物理IP:

二、上面的機器即客戶端向haproxy創建TCP三次握手:

三、從RS上看是誰跟本身創建鏈接

 

 

補充:

咱們知道HTTP協議採用「請求-應答」模式,當使用普通模式,即非KeepAlive模式時,每一個請求/應答客戶和服務器都要新建一個鏈接,完成 以後當即斷開鏈接(HTTP協議爲無鏈接的協議);當使用Keep-Alive模式(又稱持久鏈接、鏈接重用)時,Keep-Alive功能使客戶端到服 務器端的鏈接持續有效,當出現對服務器的後繼請求時,Keep-Alive功能避免了創建或者從新創建鏈接。

http 1.0中默認是關閉的,須要在http頭加入"Connection: Keep-Alive",才能啓用Keep-Alive;http 1.1中默認啓用Keep-Alive,若是加入"Connection: close ",才關閉。目前大部分瀏覽器都是用http1.1協議,也就是說默認都會發起Keep-Alive的鏈接請求了,因此是否能完成一個完整的Keep- Alive鏈接就看服務器設置狀況。

 

10、haproxy調度算法


Haproxy 8種算法+Session共享

Haproxy支持的調度算法

相關文章
相關標籤/搜索