HAproxy原理及配置
软件:haproxy---主要是做负载均衡的7层,也可以做4层负载均衡
HAPROXY配置文件中分五大部分:
- global:全局参数配置,用来控制Haproxy启动前的一些进程及系统设置。
- defaults:配置一些默认的参数,可以被frontend,- backend,listen段使用
- frontend:匹配接收客户所请求的域名,uri等,并针对匹配做不同的请求处理;
- backend:定义后端服务器集群,以及对后端服务器集群的一些权重、队列、连接数等选项的设置,类似于nginx中的upstream模块,类似于LVS中的real server节点;
- listen:可以理解为frontend和backend的组合体。
- Haproxy配置文件的配置方法主要有两种,一种是由前端(frontend)和后端(backend)配置块组成,前端和后端都可以有多个。第二种方法是只有一个listen配置块来同时实现前端和后端。最常用也是推荐的方法为第一种,即frontend和backend的模式。
global
log 127.0.0.1 local2 #日志服务器
pidfile /var/run/haproxy.pid #pid文件(进程)
maxconn 4000 #最大连接数
user haproxy #用户
group haproxy #组
daemon #守护进程方式后台运行
nbproc 1 #工作进程数量 cpu内核是几就写几
defaults #提供默认参数
mode http #工作模式 http ,tcp 是 4 层,http是 7 层
log global
option redispatch #服务不可用后重定向到其他健康服务器
retries 3 #健康检查。3次连接失败就认为服务器不可用,主要通过后面的check检查
maxconn 4000
contimeout 5000
clitimeout 50000
srvtimeout 50000
listen stats ##使用浏览器访问http://192.168.246.169/haproxy,可以看到服务器状态(web界面显示haproxy状态)
bind *:81 #自定义端口
stats enable
stats uri /haproxy #自定义URL开头
stats auth qianfeng:123 #用户认证,客户端使用elinks浏览器的时候不生效
frontend web
mode http #七层模式
bind *:80
option httplog #日志类别 http 日志格式
acl html url_reg -i \.html$ #1.访问控制列表名称html。规则要求访问以html结尾的url(可选) #acl访问控制,-i忽略大小写
use_backend xxx if html #如果满足acl html规则,则推送给后端服务器xxx
default_backend httpservers ¥设置默认后端标签
backend httpservers #名字要与上面的名字必须一样
balance roundrobin #算法:轮询
server http1 192.168.246.162:80 maxconn 2000 weight 1 check inter 1s rise 2 fall 2
server http2 192.168.246.163:80 maxconn 2000 weight 1 check inter 1s rise 2 fall 2
listen mysql
bind *:3306
mode tcp #四层模式
balance roundrobin #算法:轮询
server mysql1 192.168.246.163:3306 weight 1 check inter 1s rise 2 fall 2
server mysql2 192.168.246.162:3306 weight 1 check inter 1s rise 2 fall 2
#inter表示健康检查的间隔,单位为毫秒 可以用1s等,fall代表健康检查失败2回后放弃检查。rise代表连续健康检查成功2此后将认为服务器可用。默认的,haproxy认为服务时永远可用的,除非加上check让haproxy确认服务是否真的可用。
keepalived实现高可用+扩展对调度器Haproxy健康检查
- 思路:两台机器都做脚本
- 让Keepalived以一定时间间隔执行一个外部脚本(check_haproxy_status.sh),脚本的功能是当Haproxy失败,则关闭本机的Keepalived
[root@ha-proxy ~]# cat /etc/keepalived/check_haproxy_status.sh
#!/bin/bash
/usr/bin/curl -I http://localhost &>/dev/null
if [ $? -ne 0 ];then
# /etc/init.d/keepalived stop
systemctl stop keepalived
fi
#赋予权限
[root@ha-proxy ~]# chmod a+x /etc/keepalived/check_haproxy_status.sh
Keepalived配置
[root@ha-proxy keepalived]# vim keepalived.conf
! Configuration File for keepalived
global_defs {
router_id director1
}
#声明脚本位置
vrrp_script check_haproxy {
script "/etc/keepalived/check_haproxy_status.sh"
interval 5
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 80
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.246.17/24
}
track_script {
check_haproxy
}
}
作者:拉粑粑的丁丁
原文链接:https://www.jianshu.com/p/08a4bf2ca4aa