天天看點

Haproxy+keepalived高可用代理服務

一、haproxy和nginx的差別

Haproxy的工作模式:代理模式為http和tcp做代理,可以為多種服務做代理,它是一個專門的代理伺服器,自己不能成為web服務。

nginx的工作模式:web模式和代理,Nginx隻為WEB服務做代理。

二、安裝配置

1、安裝

# yum -y install haproxy      

注意,如果在生産中安裝,一定要注意安裝軟體的版本要落後最新版本一到兩個,否則,新版本中出現了bug無法解決将是緻命的。

2、配置詳解

************************全局配置*****************************

Global
log     127.0.0.1 local2  # 定義全局日志伺服器
chroot   /var/lib/haproxy  # 修改haproxy的工作目錄到制定的目錄,提高安全性
pidfile   /var/run/haproxy.pid # pid檔案位置
maxconn   4000      # 最大連接配接數
user    haproxy     # 服務運作時的身份,也可以用uid來表示
group    haproxy     # 服務運作時的身份所屬的組,可以用gid來表示
Daemon           # 服務以守護程序的身份運作
# turn on stats unix socket    # 預設打開UNIX socket
stats socket /var/lib/haproxy/stats # 指明unix socket 所在的位置
Node      www.a.com  # 定義目前節點的名稱,用于HA場景中多haproxy程序共享同一個IP位址時
ulimit-n    100       # 設定每程序所能夠打開的最大檔案描述符數目,預設情況下其會自動進行計算,是以不推薦修改此選項      

log

127.0

.

0.1

local2要想啟用,可以看到預設配置檔案中有這麼一行注釋

#local2.*/var/log/haproxy.log

做如下配置即可啟用

# touch /var/log/haproxy.log
# vim /etc/rsyslog.conf
$ModLoad imudp
$UDPServerRun 514
# service rsyslog restart
# tail -f /var/log/haproxy.log
Oct  6 10:45:22 localhost haproxy[22208]: 172.16.5.200:50332 [06/Oct/2013:10:45:22.852] web static/www.web1.com 6/0/2/4/32 200 45383 - - ---- 3/3/0/1/0 0/0 "GET / HTTP/1.1"      

顯示了用戶端ip和realserver主機名等資訊

**********************預設配置*********************************

defaults
mode  http      # 為http服務代理,http為7層協定,tcp4層
log   global     # 全局日志
option httplog      # 日志類别為http日志格式
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 # 請求逾時間
timeout queue  1m   # 排隊逾時
timeout connect 10s   # 連接配接逾時
timeout client  1m   # 用戶端逾時
timeout server  1m   # 伺服器端逾時
timeout http-keep-alive 10s # 保持連接配接逾時
timeout check  10s    # 健康檢測逾時
maxconn    3000   # 每個程序最大連接配接數,可以在global中配置      

************************前端代理配置******************************

frontend main *:5000  # 前端定義伺服器名稱和端口
acl url_static  path_beg -i /static /p_w_picpaths /javascript /stylesheets
acl url_static  path_end -i .jpg .gif .png .css .js
use_backend static     if url_static
default_backend       app
定義通路控制,如果符合 url_static,就代理到static,如果不是url_static,就使用預設的後端服務      

***********************後端伺服器配置*****************************

backend static
balance   roundrobin  #負載均衡排程算法
server   static 127.0.0.1:4331 check # 定義了一個後端伺服器并做健康狀況檢測
backend app
balance   roundrobin
server app1 127.0.0.1:5001 check rise 2 fall 1
server app2 127.0.0.1:5002 check rise 2 fall 1
server app3 127.0.0.1:5003 check rise 2 fall 1
server app4 127.0.0.1:5004 check rise 2 fall 1
# check rise 2 fall 1 健康狀況檢查,rise表示後端realserver從stop到start檢查的次數,fall表示從start到stop檢查的次數      

三、執行個體配置

本機ip:172.16.5.16

開啟forward轉發功能

#sysctl-wnet.ipv4.ip_forward=1

關閉防火牆

為後端ip:172.16.6.1做代理

為後端伺服器提供頁面并啟動httpd

# vim /var/www/html/index.html
<h1>welcome!</>
# service httpd start
global
log     127.0.0.1 local2
chroot   /var/lib/haproxy
pidfile   /var/run/haproxy.pid
maxconn   4000
user    haproxy
group    haproxy
daemon
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
mode          http
log           global
option         httplog
option         dontlognull
option http-server-close
option forwardfor    except 127.0.0.0/8 header X-Forward-For # 後端伺服器日志中記錄遠端用戶端ip,别忘了在後端伺服器上修改log格式
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
#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend web
bind *:80
default_backend static
也可以寫成
frontend web 172.16.5.16:80
dfault_backend static
#---------------------------------------------------------------------
# static backend for serving up p_w_picpaths, stylesheets and such
#---------------------------------------------------------------------
backend static
server   www.web1.com 172.16.6.1:80 check
stats          enable # 開啟伺服器狀态資訊
stats          hide-version # 隐藏版本資訊
stats          realm haproxy\ stats # 說明認證資訊 \ 轉譯了一個空格
stats          auth admin:admin # 認證使用者
stats          admin if TRUE # 通過認證就允許管理
stats          uri /abc # 自定義stats顯示頁面uri      

效果圖

Haproxy+keepalived高可用代理服務

單獨使用一個端口來監聽stats狀态資訊。

global
log     127.0.0.1 local2
chroot   /var/lib/haproxy
pidfile   /var/run/haproxy.pid
maxconn   4000
user    haproxy
group    haproxy
daemon
# turn on stats unix socket
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
listen stats
bind *:1080
stats          enable
stats          hide-version
stats          realm haproxy\ stats
stats          auth admin:admin
stats          admin if TRUE
stats          uri /abc
frontend web
bind *:80
default_backend static
backend static
server   www.web1.com 172.16.6.1:80 check      

效果圖:

Haproxy+keepalived高可用代理服務
Haproxy+keepalived高可用代理服務

四、負載均衡--排程算法

roundrobin動态支援權重和在伺服器運作時調整,支援慢速啟動

static-rr靜态不支援在伺服器運作時調整,不支援慢速啟動

leastconn最少連接配接,隻建議使用非常長的會話

source:後端伺服器時動态伺服器時使用,類似于nginx的iphash

Hash-type:map-based靜态hash碼取餘計算ip的hash碼除以所有的伺服器數,餘數得幾就放在第幾個伺服器上

Hash-type:consistent動态一緻性hashhash環

基于權重weight動态

uri根據使用者通路的uri來負載均衡,它也有hash表,同樣有hash-type,第一次通路的結果被負載到哪個伺服器,儲存在了hash表中,在來通路同樣的uri,就會始終到這台伺服器。

url_param根據使用者帳号資訊,将請求發往同一個伺服器,同樣有hash-type。

hdr:首部根據請求首部排程,同樣有hash-type

requestheader請求首部

reponseheader響應首部

hdr(hosts)格式

hdr(www.a.com)執行個體

一緻性hash負載均衡

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
listen stats
bind *:1080
stats          enable
stats          hide-version
stats          realm haproxy\ stats
stats          auth admin:admin
stats          admin if TRUE
stats          uri /abc
frontend web
bind *:80
default_backend static
backend static
balance   source
hash-type  consistent
server   www.web1.com 172.16.6.1:80 check weight 3
server   www.web2.com 172.16.6.2:80 check weight 1      

五、acl通路控制

frontend web
bind *:8080
default_backend static
acl abc src 172.16.5.100
redirect prefix http://172.16.5.16/def if abc      

當用戶端ip為172.16.5.100時,重定向到http://172.16.5.16/def

acl要和redirectprefix或者redirectlocation搭配使用

官方執行個體,将使用者登入後的url重定向到https安全連接配接。

acl clear   dst_port 80
acl secure   dst_port 8080
acl login_page url_beg  /login
acl logout   url_beg  /logout
acl uid_given url_reg  /login?userid=[^&]+
acl cookie_set hdr_sub(cookie) SEEN=1
redirect prefix  https://mysite.com set-cookie SEEN=1 if !cookie_set
redirect prefix  https://mysite.com      if login_page !secure
redirect prefix  http://mysite.com drop-query if login_page !uid_given
redirect location http://mysite.com/      if !login_page secure
redirect location / clear-cookie USERID=    if logout      

通路阻止

frontend web
bind *:8080
default_backend static
acl abc src 172.16.5.100
block if abc  # 阻止通路      
Haproxy+keepalived高可用代理服務

修改原配置檔案,實作動靜分離

frontend web
bind *:80
acl url_static    path_beg    -i /static /p_w_picpaths /javascript /stylesheets
#字元形式
acl url_static    path_reg    -i ^/static ^/p_w_picpaths ^/javascript ^/stylesheets
#正規表達式
acl url_static    path_end    -i .jpg .jpeg .gif .png .css .js
#字元
acl url_static    path_reg   -i .jpg $.jpeg$ .gif $.png$ .css$ .js$
# 正規表達式
#一般能用字元,就不要用正規表達式,字元的比正規表達式快。
use_backend static_servers     if url_static
default_backend dynamic_servers
backend static_servers
balance roundrobin
server imgsrv1 172.16.200.7:80 check maxconn 6000
server imgsrv2 172.16.200.8:80 check maxconn 6000
backend dynamic_servers
balance source
server websrv1 172.16.200.7:80 check maxconn 1000
server websrv2 172.16.200.8:80 check maxconn 1000
server websrv3 172.16.200.9:80 check maxconn 1000      

haproxylisten配置示例:

listen webfarm
bind 192.168.0.99:80
mode http
stats enable
stats auth someuser:somepassword
balance roundrobin
cookie JSESSIONID prefix
option httpclose
option forwardfor
option httpchk HEAD /check.txt HTTP/1.0
server webA 192.168.0.102:80 cookie A check
server webB 192.168.0.103:80 cookie B check      

Haproxy綜合配置事例

global
pidfile /var/run/haproxy.pid
log 127.0.0.1 local0 info
defaults
mode http
clitimeout   600000
srvtimeout   600000
timeout connect 8000
stats enable
stats auth  admin:admin
stats uri/monitor
stats refresh5s
option httpchk GET /status
retries5
option redispatch
errorfile 503 /path/to/503.text.file
balanceroundrobin# each server is used in turns, according to assigned weight
frontend http
bind :80
monitor-uri  /haproxy # end point to monitor HAProxy status (returns 200)
acl api1 path_reg ^/api1/?
acl api2 path_reg ^/api2/?
use_backend api1 if api1
use_backend api2 if api2
backend api1
# option httpclose
server srv0 172.16.5.15:80 weight 1 maxconn 100 check inter 4000
server srv1 172.16.5.16:80 weight 1 maxconn 100 check inter 4000
server srv2 172.16.5.16:80 weight 1 maxconn 100 check inter 4000
backend api2
option httpclose
server srv01 172.16.5.18:80 weight 1 maxconn 50 check inter 4000      

六、結合keepalived做高可用代理

拓撲圖

Haproxy+keepalived高可用代理服務

規劃:

準備工作請參照之前寫的部落格,無非就是時間同步,雙機互信,主機名稱能夠互相解析。

node1:

ip:172.16.5.15

hostname:www.a.com

node2

ip:172.16.5.16

hostname:www.b.com

後端realserver讓别人代做

配置haproxy

node1:# yum -y install haproxy
node2:# yum -y install haproxy
# cd /etc/haproxy
# mv haproxy.cfg haproxy.bak
# vim haproxy.cfg
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 header X-Forward-For
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
listen stats #專門弄個端口進行狀态管理
bind *:1080
stats                   enable
stats                   hide-version
stats                   realm haproxy\ stats
stats                   auth admin:admin
stats                   admin if TRUE
stats                   uri /abc
frontend web
    bind *:80
    acl danymic path_end -i .php
    acl abc src 172.16.5.100
    block if abc
    use_backend php if danymic
    default_backend static
backend static
    balance     roundrobin
    server      www.web1.com 172.16.5.16:8080 check rise 2 fall 1 weight 1
    server      www.web2.com 172.16.5.15:8080 check rise 2 fall 1 weight 1
backend php
    balance roundrobin
    server    www.web3.com 172.16.6.1:80 check rise 2 fall 1 weight 1
    server    www.web4.com 172.16.6.2:80 check rise 2 fall 1 weight 1
# scp haproxy.cfg b:/etc/haproxy/      

配置keepalived

node1

# yum -y install keepalived
# cd /etc/keepalived/
# vim keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
[email protected]
[email protected]
[email protected]
}
notification_email_from [email protected]
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_haproxy {
script "killall -0 haproxy"
interval 1
weight 2
}
#vrrp_script chk_mantaince_down {
#   script "[[ -f /etc/keepalived/down ]] && exit 1 || exit 0"
#   interval 1
#   weight 2
#}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 5
priority 99
advert_int 1
authentication {
auth_type PASS
auth_pass 11111
}
virtual_ipaddress {
172.16.5.100/16
}
track_script {
chk_mantaince_down
chk_haproxy
}
notify_master "/etc/keepalived/notify.sh master"
notify_backup "/etc/keepalived/notify.sh backup"
notify_fault "/etc/keepalived/notify.sh fault"
}
vrrp_instance VI_2 {
state MASTER
interface eth0
virtual_router_id 50
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 11111
}
virtual_ipaddress {
172.16.5.101/16
}
track_script {
chk_mantaince_down
chk_haproxy
}
notify_master "/etc/keepalived/notify.sh master"
notify_backup "/etc/keepalived/notify.sh backup"
notify_fault "/etc/keepalived/notify.sh fault"
}      

該配置檔案主要實作的功能:1、兩個執行個體VI,實作了雙主模型,主要為前端dns負載均衡使用;2、單個主從模型可以實作高可用,前提是若是針對某個服務,這個服務必須在keepalived啟動之前啟動,而且要對之監控;3、當然,也要做好對keepalived服務本身的監控,這就需要編輯另外的腳本,腳本所在的目錄必須與notify_master"/etc/keepalived/notify.shmaster"中提到的一緻。

編寫對keepalived服務本身的監控腳本

# vim /etc/keepalived/notify.sh
#!/bin/bash
# Author: MageEdu <[email protected]>
# description: An example of notify script
#
vip=172.16.5.100
contact='[email protected]'
Notify() {
mailsubject="`hostname` to be $1: $vip floating"
mailbody="`date '+%F %H:%M:%S'`: vrrp transition, `hostname` changed to be $1"
echo $mailbody | mail -s "$mailsubject" $contact
}
case "$1" in
master)
notify master
/etc/rc.d/init.d/haproxy start
exit 0
;;
backup)
notify backup
/etc/rc.d/init.d/haproxy restart
exit 0
;;
fault)
notify fault
exit 0
;;
*)
echo 'Usage: `basename $0` {master|backup|fault}'
exit 1
;;
esac      

注意:本腳本中提到了vip,而本實驗是雙主模型,其中有兩個vip,如果想省事,就寫一個就行了,如果求精确,可以複制這個腳本,修改vip然後在配置檔案中修改另一個執行個體中的notify.sh的路徑。

node2中也要這樣配置,不過要修改主從和優先級,這裡不再羅嗦。

配置完之後,啟動了haproxy和keepalived之後,對配置做下校驗。

#service haproxy start
#service keepalived start
node1
# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:a5:31:22 brd ff:ff:ff:ff:ff:ff
inet 172.16.5.15/16 brd 172.16.255.255 scope global eth0
inet 172.16.5.101/16 scope global secondary eth0
inet6 fe80::20c:29ff:fea5:3122/64 scope link
valid_lft forever preferred_lft forever
node2
# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:cc:55:6d brd ff:ff:ff:ff:ff:ff
inet 172.16.5.16/16 brd 172.16.255.255 scope global eth0
inet 172.16.5.100/16 scope global secondary eth0
inet6 fe80::20c:29ff:fecc:556d/64 scope link
valid_lft forever preferred_lft forever      

驗證效果

###########################keepalived的雙主模型實作的負載均衡##################################

Haproxy+keepalived高可用代理服務
Haproxy+keepalived高可用代理服務

############################動靜分離之靜态頁面負載均衡############################

Haproxy+keepalived高可用代理服務
Haproxy+keepalived高可用代理服務

############################動靜分離之動态頁面負載均衡##############################

Haproxy+keepalived高可用代理服務
Haproxy+keepalived高可用代理服務

**************************************************************************************************通路專門設定的用于檢視代理狀态的頁面

Haproxy+keepalived高可用代理服務

**************************************************************************************************修改配置檔案,将拒絕通路的ip改為用戶端ip,得到如下頁面

frontendweb

bind*:80

default_backendstatic

aclabcsrc172.16.5.200

blockifabc

172.16.5.200是我實體機的IP位址

Haproxy+keepalived高可用代理服務

以上總結,有不足之處,望指教。。

轉載于:https://blog.51cto.com/qiufengsong/1304925