一、HAproxy簡介
1)HAProxy提供高可用性、負載均衡以及基於TCP和HTTP應用的代理,支持虛擬主機,它是免費、快速並且可靠的一種解決方案。
2)HAProxy特別適用於那些負載特大的web站點,這些站點通常又需要會話保持或七層處理。
3)HAProxy運行在當前的硬件上,完全可以支持數以萬計的併發連接。並且它的運行模式使得它可以很簡單安全的整合進您當前的架構中, 同時可以保護你的web服務器不被暴露到網絡上。
---------------------
二、環境配置
服務器系統:debian 8 jessie
nginx: nginx/1.14.0
服務器模擬: 分別使用本機的8080和9080端口
ip地址: 192.168.1.124
mysql: 192.168.1.124:3307 192.168.1.39:3306(我此處設置的賬號密碼一致ops:ops1300.)
三、安裝haproxy
下載:http://www.haproxy.org/download/1.7/src/haproxy-1.7.9.tar.gz
編譯安裝
root@centos-mysql01:/data#tar zxf haproxy-1.7.9.tar.gz root@centos-mysql01:/data#cd haproxy-1.7.9 root@centos-mysql01:/data#make TARGET=linux31 prefix=/usr/local/haproxy root@centos-mysql01:/data#make install PREFIX=/usr/local/haproxy |
四、配置haproxy
創建haproxy用戶
root@centos-mysql01:/data#userdel -g 1004 haproxy root@centos-mysql01:/data#useradd haproxy -u 1004 -d /usr/local/haproxy -s /sbin/nologin -g haproxy |
創建對應文件目錄
root@centos-mysql01:/data#mkdir /usr/local/haproxy/conf root@centos-mysql01:/data#mkdir /usr/local/haproxy/logs |
整理配置文件
Haproxy配置中分成五部分內容,當然這些組件不是必選的,可以根據需要選擇作爲配置。 global:參數是進程級的,通常和操作系統(OS)相關。這些參數一般只設置一次,如果配置無誤,就不需要再次配置進行修改; default:配置默認參數的,這些參數可以被利用配置到frontend,backend,listen組件; frontend:接收請求的前端虛擬節點,Frontend可以根據規則直接指定具體使用後端的backend(可動態選擇); backend:後端服務集羣的配置,是真實的服務器,一個Backend對應一個或者多個實體服務器; listen:Frontend和Backend的組合體。 mode http #默認的模式mode { tcp|http|health },tcp是4層,http是7層,health只會返回OK #retries 2 #兩次連接失敗就認爲是服務器不可用,也可以通過後面設置 option redispatch #當serverId對應的服務器掛掉後,強制定向到其他健康的服務器 option abortonclose #當服務器負載很高的時候,自動結束掉當前隊列處理比較久的鏈接 timeout connect 5000ms #連接超時 timeout client 30000ms #客戶端超時 timeout server 30000ms #服務器超時 #timeout check 2000 #=心跳檢測超時 log 127.0.0.1 local0 err #[err warning info debug] balance roundrobin #負載均衡算法 #option httplog #日誌類別,採用httplog #option httpclose #每次請求完畢後主動關閉http通道,ha-proxy不支持keep-alive,只能模擬這種模式的實現 #option dontlognull #option forwardfor #如果後端服務器需要獲得客戶端真實ip需要配置的參數,可以從Http Header中獲得客戶端ip |
root@centos-mysql01:/usr/local/haproxy# cat conf/haproxy.cfg #haproxy.cfg global log 127.0.0.1 local0 maxconn 4096 #最大連接數 chroot /usr/local/haproxy #安裝目錄 uid 1004 #用戶haproxy gid 1004 #組haproxy daemon #守護進程運行 nbproc 1 #進程數量 pidfile /usr/local/haproxy/logs/haproxy.pid #haproxy pid
defaults log global mode http #7層 http;4層tcp 如果要讓haproxy支持虛擬主機,mode 必須設爲http # option httplog #http 日誌格式 如果後面listen代理tcp的需要註釋掉此項目 log 127.0.0.1 local6 option httpclose #主動關閉http通道 option redispatch #serverId對應的服務器掛掉後,強制定向到其他健康的服務器 retries 1 option dontlognull maxconn 2000 #最大連接數 timeout connect 3600000 #連接超時(毫秒) timeout client 3600000 #客戶端超時(毫秒) timeout server 3600000 #服務器超時(毫秒) frontend default option httplog option httpclose bind 0.0.0.0:8888 acl haproxy_stats path_beg /haproxy use_backend haproxy_stats if haproxy_stats backend haproxy_stats stats uri /haproxy stats enable stats refresh 60s #stats auth admin:admin # 狀態頁面認證配置 stats admin if TRUE frontend hanye option httplog option httpclose mode http option forwardfor option forwardfor header Client-IP option http-server-close bind *:80 acl web hdr(host) -i web.hz7726.com acl img hdr(host) -i img.hz7726.com use_backend webserver if web use_backend imgserver if img default_backend nginx
backend nginx balance roundrobin server nginx1 192.168.1.124:8080 check inter 2s rise 3 fall 3 weight 3 server nginx2 192.168.1.124:9080 check inter 2s rise 3 fall 3 weight backend webserver balance roundrobin option httpchk HEAD /index.html HTTP/1.1\r\nHost:\ web.hz7726.com server web1 192.168.1.124:8080 cookie check inter 2s rise 3 fall 3 weight 3 backend imgserver balance roundrobin option httpchk HEAD /index.html HTTP/1.1\r\nHost:\ img.hz7726.com server img1 192.168.1.124:9080 cookie check inter 2s rise 3 fall 3 weight 3 listen mysql_demo bind 0.0.0.0:3306 mode tcp balance roundrobin server mysql1 192.168.1.39:3306 weight 1 check inter 1s rise 2 fall 2 server mysql2 192.168.1.124:3307 weight 1 check inter 1s rise 2 fall 2 |
整理啓動腳本
我這裏是直接複製的張哥的(來自:https://zhangge.net/5125.html)
#!/bin/bash ################################################################### ################################################################### # chkconfig: 35 10 90 export PATH=/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:$PATH PROCESS_NAME=haproxy BASE_DIR=/usr/local/haproxy EXEC=$BASE_DIR/sbin/haproxy PID_FILE=$BASE_DIR/logs/haproxy.pid DEFAULT_CONF=$BASE_DIR/conf/haproxy.cfg MONLOG_PATH="$BASE_DIR/logs/${PROCESS_NAME}_mon.log"
# COLOR print COLOR_RED=$( echo -e "\e[31;49m" ) COLOR_GREEN=$( echo -e "\e[32;49m" ) COLOR_RESET=$( echo -e "\e[0m" ) info() { echo "${COLOR_GREEN}$*${COLOR_RESET}" ;} warn() { echo "${COLOR_RED}$*${COLOR_RESET}" ;}
do_log() { local log_fpath=$1 local log_content=$2 echo "$(date '+%F %T') $log_content" >> $log_fpath }
print_usage() { echo info " Usage: $(basename $0) [start|stop|restart|mon|test]" echo }
#get Expanding configuration ext_configs() { CONFIGS= if [[ -d $BASE_DIR/conf/enabled ]];then for FILE in $(find $BASE_DIR/conf/enabled -type l | sort -n) do CONFIGS="$CONFIGS -f $FILE"; done echo $CONFIGS else echo fi } # check process status check_process() { PID=`get_pid` if ps aux | awk '{print $2}' | grep -qw $PID 2>/dev/null ;then true else false fi
} # check Configuration file check_conf() { $EXEC -c -f $DEFAULT_CONF `ext_configs` >/dev/null 2>&1 return $? } get_pid() { if [[ -f $PID_FILE ]];then cat $PID_FILE else warn " $PID_FILE not found!" exit 1 fi } start() { echo if check_process;then warn " ${PROCESS_NAME} is already running!" else $EXEC -f $DEFAULT_CONF `ext_configs` && \ echo -e " ${PROCESS_NAME} start [ `info OK` ]" || \ echo -e " ${PROCESS_NAME} start [ `warn Failed` ]" fi echo }
stop() { echo if check_process;then PID=`get_pid` kill -9 $PID >/dev/null 2>&1 echo -e " ${PROCESS_NAME} stop [ `info OK` ]" else warn " ${PROCESS_NAME} is not running!" fi echo }
restart() { echo if check_process;then : else warn " ${PROCESS_NAME} is not running! Starting Now..." fi if `check_conf`;then PID=`get_pid` $EXEC -f $DEFAULT_CONF `ext_configs` -st $PID && \ echo -e " ${PROCESS_NAME} restart [ `info OK` ]" || \ echo -e " ${PROCESS_NAME} restart [ `warn Failed` ]" else warn " ${PROCESS_NAME} Configuration file is not valid, plz check!" echo -e " ${PROCESS_NAME} restart [ `warn Failed` ]" fi echo }
mon() { if check_process;then info "${PROCESS_NAME} is running OK!" do_log $MONLOG_PATH "${PROCESS_NAME} is running OK!" else start warn " ${PROCESS_NAME} not running, start it!" do_log $MONLOG_PATH "${PROCESS_NAME} not running, plz check" fi }
if [[ $# != 1 ]]; then print_usage exit 1 else case $1 in "start"|"START") start ;; "stop"|"STOP") stop ;; "restart"|"RESTART"|"-r") restart ;; "status"|"STATUS") if check_process;then info "${PROCESS_NAME} is running OK!" else warn " ${PROCESS_NAME} not running, plz check" fi ;; "test"|"TEST"|"-t") echo if check_conf ;then info " Configuration file test Successfully." else warn " Configuration file test failed." fi echo ;; "mon"|"MON"|"-m") mon ;; *) print_usage exit 1 esac fi |
註冊系統服務
root@centos-mysql01:chmod +x /usr/local/haproxy/sbin/ctrl.sh root@centos-mysql01:ln -sf /usr/local/haproxy/sbin/ctrl.sh /etc/init.d/haproxy root@centos-mysql01:chkconfig haproxy on 啓動:service haproxy start 停止:service haproxy stop 重載:service haproxy restart 狀態:service haproxy status 檢查:service haproxy test 監控:service haproxy mon # 進程自拉起,如有告警通道可自行加入 |
配置自動拉起
* * * * * bash /usr/local/haproxy/ctrl.sh mon >/dev/null 2>&1
注意:開啓rsyslog的local6日誌存放
vim /etc/rsyslog.conf
#新增配置
local6.* /usr/local/haproxy/logs/rsyslog_haproxy.log
#取消如下2行註釋
$ModLoad imudp
$UDPServerRun 514
#重啓syslog服務
五、啓動測試
1. stats狀態:
2.nginx負載狀態
自己多刷新幾次對比下
3.mysql負載
listen mysql_demo bind 0.0.0.0:3306 mode tcp balance roundrobin server mysql1 192.168.1.39:3306 weight 1 check inter 1s rise 2 fall 2 server mysql2 192.168.1.124:3307 weight 1 check inter 1s rise 2 fall 2 |
訪問對比