一、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 |
访问对比