运维开发宝典048-七层负载均衡集群2

📅 2026/7/2 5:05:45
运维开发宝典048-七层负载均衡集群2
大家好我是云计算磊哥从业20年的IT老鸟。IT架构师培训15年总结了一套从入门到精通的全运维开发宝典手册。准备用300天时间写一套博文手把手从安装软件讲起从linux系统管理shell脚本编程mysql运维架构备份核心技术Apache/nginx/tomcatWEB服务器管理ansible自动化运维redis集群哨兵LVM/HAproxy/keepalived集群架构rabbitMQ消息队列dockerK8S集群资源管理K8S自愈K8S自动扩容PYTHON编程基础PYTHON自动化运维从行业到产品从过去到未来从理论到操作从视频到文档工具100篇系列文章一站式发布。从零基础入门到30k运维开发工程师岗位诸多就业问题。多方位全方面的给你讲清楚云计算这个行业该如何做。关注我。后续AI大模型开发课程更精彩。七层负载均衡集群四、专业负载均衡器Haproxy扩展![外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传](https://img-home.csdnimg.cn/images/20230724024159.png?origin_url%E8%BF%90%E7%BB%B4%E5%BC%80%E5%8F%91%E5%AE%9D%E5%85%B8048-%E4%B8%83%E5%B1%82%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1%E9%9B%86%E7%BE%A42.assets%2Fpos_idimg-1YT9mQqF-1782895051227)1、HAProxy简介官网http://www.haproxy.comHAProxy提供高可用性、负载均衡以及基于TCP和HTTP的应用代理支持虚拟主机它是免费、快速并且可靠的一种负载均衡解决方案。适合处理高负载站点的七层数据请求。类似的代理服务可以屏蔽内部真实服务器防止内部服务器遭受攻击。1、HAProxy 特点和优点支持原生SSL,同时支持客户端和服务器的SSL.支持IPv6和UNIX套字节sockets支持HTTP Keep-Alive支持HTTP/1.1压缩节省宽带支持优化健康检测机制SSL、scripted TCP、check agent…支持7层负载均衡。可靠性和稳定性非常好。并发连接40000-50000个单位时间处理最大请求20000个最大数据处理10Gbps.支持8种负载均衡算法同时支持session保持。支持虚拟主机。支持连接拒绝、全透明代理。拥有服务器状态监控页面。支持ACL.2、 HAProxy 保持会话HAProxy为了让同一客户端访问服务器可以保持会话。有三种解决方法客户端IP、Cookie以及SessionHAProxy通过客户端IP进行Hash计算并保存以此确保当相同IP访问代理服务器可以转发给固定的真实服务器。HAProxy依靠真实服务器发送客户端的Cookie信息进行会话保持。HAProxy将保存真实服务器的Session以及服务器标识实现会话保持。HAProxy只要求后端服务器能够在网络联通也没有像LVS那样繁琐的ARP配置3、HAProxy 负载均衡算法HAProxy的balance8种负载均衡算法roundrobin : 基于权重轮循。static-rr : 基于权重轮循。静态算法运行时改变无法生效source : 基于请求源IP的算法。对请求的源IP进行hash运算然后将结果与后端服务器的权重总数想除后转发至某台匹配服务器。使同一IP客户端请求始终被转发到某特定的后端服务器。leastconn : 最小连接。适合数据库负载均衡不适合会话短的环境uri : 对部分或整体URI进行hash运算再与服务器的总权重想除最后转发到匹配后端。uri_param : 根据URL路径中参数进行转发保证在后端服务器数量不变的情况下同一用户请求分发到同一机器。hdr() : 根据http头转发如果不存在http头。则使用简单轮循。4、HAProxy主要工作模式tcp模式:该模式下在客户端和服务器之间将建立一个全双工的连接且不会对7层的报文做任何处理的简单模式。此模式默认通常用于SSL、SSH、SMTP应用。http模式一般使用该模式下客户端请求在转发给后端服务器之前会被深度分析所有不与RFC格式兼容的请求都会被拒绝。2、HAProxy 安装及配置文件参数1、HAProxy 安装[rootxulei.com ~]# yum -y install haproxy2、HAProxy 环境haproxy 的配置文件通常分为三部分:global全局配置部分defaults默认配置部分listen(应用组件部分)1、 HAProxy 配置文件详解[rootxulei.com ~]# vim /etc/haproxy/haproxy.cfg####################全局配置##############################参数是进程级的通常和操作系统OS相关#########global maxconn20480# 默认最大连接数log127.0.0.1 local0# 日志输出配置所有日志都记录在本机系统日志通过local0输出log127.0.0.1 local1 notice# notice 为日志级别通常有24个级别error warringinfo debugchroot/var/haproxy# chroot运行的路径uid99# 所属运行的用户uidgid99# 所属运行的用户组daemon# 以后台形式运行haproxynbproc1# 进程数量(可以设置多个进程提高性能)pidfile /var/run/haproxy.pid# haproxy的pid存放路径,启动进程的用户必须有权限访问此文件ulimit-n65535# ulimit的数量限制#####################默认设置########################这些参数可以被利用配置到frontendbackendlisten组件##defaults log global mode http# 所处理的类别 (#7层 http;4层tcp )maxconn20480# 最大连接数option httplog# 日志类别http日志格式option httpclose# 每次请求完毕后主动关闭http通道option dontlognull# 不记录健康检查的日志信息option forwardfor# 如果后端服务器需要获得客户端真实ip需要配置的参数可以从Http Header中获得客户端ipoption redispatch# serverId对应的服务器挂掉后,强制定向到其他健康的服务器option abortonclose# 当服务器负载很高的时候自动结束掉当前队列处理比较久的连接stats refresh30# 统计页面刷新间隔retries3# 3次连接失败就认为服务不可用也可以通过后面设置balance roundrobin# 默认的负载均衡的方式,轮询方式#balance source # 默认的负载均衡的方式,类似nginx的ip_hash#balance leastconn # 默认的负载均衡的方式,最小连接contimeout5000# 连接超时clitimeout50000# 客户端超时srvtimeout50000# 服务器超时timeoutcheck2000# 心跳检测超时####################监控页面的设置#######################listen admin_status# Frontend和Backend的组合体,监控组的名称按需自定义名称bind0.0.0.0:65532# 监听端口mode http# http的7层模式log127.0.0.1 local3 err# 错误日志记录stats refresh 5s# 每隔5秒自动刷新监控页面stats uri /admin?stats# 监控页面的urlstats realm itnihao\itnihao# 监控页面的提示信息stats auth admin:admin# 监控页面的用户和密码admin,可以设置多个用户名stats auth admin1:admin1# 监控页面的用户和密码admin1stats hide-version# 隐藏统计页面上的HAproxy版本信息stats adminifTRUE# 手工启用/禁用,后端服务器(haproxy-1.4.9以后版本)errorfile403/etc/haproxy/errorfiles/403.http errorfile500/etc/haproxy/errorfiles/500.http errorfile502/etc/haproxy/errorfiles/502.http errorfile503/etc/haproxy/errorfiles/503.http errorfile504/etc/haproxy/errorfiles/504.http#################HAProxy的日志记录内容设置###################capture request header Host len40capture request header Content-Length len10capture request header Referer len200capture response header Server len40capture response header Content-Length len10capture response header Cache-Control len8#######################网站监测listen配置################################此用法主要是监控haproxy后端服务器的监控状态############listen site_statusbind0.0.0.0:1081# 监听端口mode http# http的7层模式log127.0.0.1 local3 err# [err warning info debug]monitor-uri /site_status# 网站健康检测URL用来检测HAProxy管理的网站是否可以用正常返回200不正常返回503acl site_dead nbsrv(server_web)lt2# 定义网站down时的策略当挂在负载均衡上的指定backend的中有效机器数小于1台时返回trueacl site_dead nbsrv(server_blog)lt2acl site_dead nbsrv(server_bbs)lt2monitor failifsite_dead# 当满足策略的时候返回503网上文档说的是500实际测试为503monitor-net192.168.16.2/32# 来自192.168.16.2的日志信息不会被记录和转发monitor-net192.168.16.3/32######################frontend配置##############################注意frontend配置里面可以定义多个acl进行匹配操作###########frontend http_80_inbind0.0.0.0:80# 监听端口即haproxy提供web服务的端口和lvs的vip端口类似mode http# http的7层模式log global# 应用全局的日志配置option httplog# 启用http的logoption httpclose# 每次请求完毕后主动关闭http通道HA-Proxy不支持keep-alive模式option forwardfor# 如果后端服务器需要获得客户端的真实IP需要配置次参数将可以从Http Header中获得客户端IP########################acl策略配置########################acl itnihao_web hdr_reg(host)-i^(www.itnihao.cn|ww1.itnihao.cn)$# 如果请求的域名满足正则表达式中的2个域名返回true -i是忽略大小写acl itnihao_blog hdr_dom(host)-iblog.itnihao.cn# 如果请求的域名满足www.itnihao.cn返回true -i是忽略大小写# acl itnihao hdr(host) -i itnihao.cn# 如果请求的域名满足itnihao.cn返回true -i是忽略大小写# acl file_req url_sub -i killall# 在请求url中包含killall则此控制策略返回true,否则为false# acl dir_req url_dir -i allow# 在请求url中存在allow作为部分地址路径则此控制策略返回true,否则返回false# acl missing_cl hdr_cnt(Content-length) eq 0# 当请求的header中Content-length等于0时返回true##########################acl策略匹配相应################### block if missing_cl# 当请求中header中Content-length等于0阻止请求返回403# block if !file_req || dir_req# block表示阻止请求返回403错误当前表示如果不满足策略file_req或者满足策略dir_req则阻止请求use_backend server_webifitnihao_web# 当满足itnihao_web的策略时使用server_web的backenduse_backend server_blogifitnihao_blog# 当满足itnihao_blog的策略时使用server_blog的backend# redirect prefix http://blog.itniaho.cn code 301 if itnihao# 当访问itnihao.cn的时候用http的301挑转到http://192.168.16.3default_backend server_bbs# 以上都不满足的时候使用默认server_bbs的backend########################backend的设置#####################下面我将设置三组服务器 server_webserver_blogserver_bbs###########################backend server_web#############################backend server_web mode http# http的7层模式balance roundrobin# 负载均衡的方式roundrobin平均方式cookie SERVERID# 允许插入serverid到cookie中serverid后面可以定义option httpchk GET /index.html# 心跳检测的文件server web1192.168.16.2:80 cookie web1 check inter1500rise3fall3weight1# 服务器定义cookie 1表示serverid为web1check inter 1500是检测心跳频率rise 3是3次正确认为服务器可用# fall 3是3次失败认为服务器不可用weight代表权重server web2192.168.16.3:80 cookie web2 check inter1500rise3fall3weight2# 服务器定义cookie 1表示serverid为web2check inter 1500是检测心跳频率rise 3是3次正确认为服务器可用# fall 3是3次失败认为服务器不可用weight代表权重###################################backend server_blog###############################################backend server_blog mode http# http的7层模式balance roundrobin# 负载均衡的方式roundrobin平均方式cookie SERVERID# 允许插入serverid到cookie中serverid后面可以定义option httpchk GET /index.html# 心跳检测的文件server blog1192.168.16.2:80 cookie blog1 check inter1500rise3fall3weight1# 服务器定义cookie 1表示serverid为web1check inter 1500是检测心跳频率rise 3是3次正确认为服务器可用fall 3是3次失败认为服务器不可用weight代表权重server blog2192.168.16.3:80 cookie blog2 check inter1500rise3fall3weight2# 服务器定义cookie 1表示serverid为web2check inter 1500是检测心跳频率rise 3是3次正确认为服务器可用fall 3是3次失败认为服务器不可用weight代表权重###################################backend server_bbs###############################################backend server_bbs mode http# http的7层模式balance roundrobin# 负载均衡的方式roundrobin平均方式cookie SERVERID# 允许插入serverid到cookie中serverid后面可以定义option httpchk GET /index.html# 心跳检测的文件server bbs1192.168.16.2:80 cookie bbs1 check inter1500rise3fall3weight1# 服务器定义cookie 1表示serverid为web1check inter 1500是检测心跳频率rise 3是3次正确认为服务器可用fall 3是3次失败认为服务器不可用weight代表权重server bbs2192.168.16.3:80 cookie bbs2 check inter1500rise3fall3weight2# 服务器定义cookie 1表示serverid为web2check inter 1500是检测心跳频率rise 3是3次正确认为服务器可用fall 3是3次失败认为服务器不可用weight代表权重3、Haproxy 实现七层负载Keepalived Haproxy[rootxulei.com. ~]# vim /etc/haproxy/haproxy.cfgglobal#关于进程的全局参数log127.0.0.1 local2chroot/var/lib/haproxy pidfile /var/run/haproxy.pid maxconn4000user haproxy group haproxy daemon defaults、listen、frontend、backend# 关于Proxy配置段defaults# 段用于为其它配置段提供默认参数listen是frontend和backend的结合体 frontend# 虚拟服务VIrtual Server 监听器 接受访问并调度backend# 真实服务器Real Server Web Servers 被调度的服务器# 调度器可以同时为多个站点调度如果使用frontend、backend的方式frontend1 backend1 frontend2 backend2 frontend3 backend3Keepalived Haproxy拓扑结构[vip:192.168.122.100][LB1 Haproxy][LB2 Haproxy]192.168.122.2192.168.122.3[httpd][httpd][httpd]192.168.122.10192.168.122.20192.168.122.30 一、Haproxy实施步骤1. 准备工作集群中所有主机 IP, hostname, hosts, iptables, SELinux,sshtrust, ntp[rootxulei.com. ~]# cat /etc/hosts127.0.0.1 localhost192.168.122.2 director1.xulei.com active192.168.122.3 director2.xulei.com backup192.168.122.10 node1.xulei.com node1192.168.122.20 node2.xulei.com node2192.168.122.30 node2.xulei.com node32. RS配置 配置好网站服务器测试所有RS3. 调度器配置Haproxy主/备[rootxulei.com. ~]# yum -y install haproxy[rootxulei.com. ~]# cp -rf /etc/haproxy/haproxy.cfg{,.bak}[rootxulei.com. ~]# sed -i -r /^[ ]*#/d;/^$/d /etc/haproxy/haproxy.cfg[rootxulei.com. ~]# vim /etc/haproxy/haproxy.cfgglobal... defaults... ----------------------------配置监控[可选]------------------------------ listen statsbind*:1314 statsenablestats refresh 30s stats hide-version stats uri /haproxystats stats realm Haproxy\stats stats auth qfedu:123 stats adminifTRUE ---------------------------------------------------------------------- frontend web mode httpbind*:80 default_backend httpservers backend httpservers balance roundrobin server http1192.168.122.10:80 maxconn2000weight1check inter 1s rise2fall2server http2192.168.122.20:80 maxconn2000weight1check inter 1s rise2fall2server http3192.168.122.30:80 maxconn2000weight1check inter 1s rise2fall2[rootxulei.com. ~]# service haproxy restart[rootxulei.com. ~]# chkconfig haproxy on测试调度器(主/备)Keepalived 实现调度器 HA 注主/备调度器均能够实现正常调度1. 主/备调度器安装软件[rootmaster.xulei.com ~]# yum -y install keepalived[rootbackup.xulei.com ~]# yum -y install keepalived2. Keepalived Master[rootmaster.xulei.com ~]# vim /etc/keepalived/keepalived.conf!Configuration Fileforkeepalived global_defs{router_id director1# 辅助改为director2}vrrp_instance VI_1{state BACKUP nopreempt interface eth0# 心跳接口尽量单独连接心跳virtual_router_id80# MASTER,BACKUP一致priority100# 辅助改为50advert_int1authentication{auth_type PASS auth_pass1111}virtual_ipaddress{192.168.122.100}}BACKUP3. 启动KeepAlived主备均启动[rootbackup.xulei.com ~]# systemctl enable keeplived[rootbackup.xulei.com ~]# systemctl start keepalived[rootbackup.xulei.com ~]# ip addr4. 扩展对调度器Haproxy健康检查可选 思路 让Keepalived以一定时间间隔执行一个外部脚本脚本的功能是当Haproxy失败则关闭本机的Keepalived a. script[rootmaster.xulei.com ~]# cat /etc/keepalived/check_haproxy_status.sh#!/bin/bash/usr/bin/curl-Ihttp://localhost/dev/nullif[$?-ne0];then/etc/init.d/keepalived stopfi[rootmaster.xulei.com ~]# chmod ax /etc/keepalived/check_haproxy_status.shb. keepalived使用script!Configuration Fileforkeepalived global_defs{router_id director1}vrrp_script check_haproxy{script/etc/keepalived/check_haproxy_status.shinterval5}vrrp_instance VI_1{state BACKUP interface eth0 nopreempt virtual_router_id90priority100advert_int1authentication{auth_type PASS auth_pass qfedu}virtual_ipaddress{192.168.122.100}track_script{check_haproxy}}listen www.xulei.com mode httpbind*:80 balance roundrobin#balance sourceserver http1192.168.122.10:80 maxconn2000weight1check inter 1s rise2fall2server http2192.168.122.20:80 maxconn2000weight1check inter 1s rise2fall2server http3192.168.122.30:80 maxconn2000weight1check inter 1s rise2fall2Haproxy Log:[rootrhel6 ~]# tcpdump -i lo -nn port 514tcpdump: verbose output suppressed, use-vor-vvforfull protocol decode listening on lo, link-type EN10MB(Ethernet), capture size65535bytes 02:48:50.475524 IP127.0.0.1.41350127.0.0.1.514: SYSLOG local2.info, length:17602:48:55.479321 IP127.0.0.1.41350127.0.0.1.514: SYSLOG local2.info, length:17602:49:00.479946 IP127.0.0.1.41350127.0.0.1.514: SYSLOG local2.info, length:17602:49:05.476149 IP127.0.0.1.41350127.0.0.1.514: SYSLOG local2.info, length:17602:49:10.473743 IP127.0.0.1.41350127.0.0.1.514: SYSLOG local2.info, length:17602:49:15.481521 IP127.0.0.1.41350127.0.0.1.514: SYSLOG local2.info, length:176[rootmaster.xulei.com ~]# netstat -tunlp |grep :514[rootmaster.xulei.com ~]# vim /etc/sysconfig/rsyslogSYSLOGD_OPTIONS-c 2 -r[rootmaster.xulei.com ~]# vim /etc/rsyslog.conf# Provides UDP syslog reception$ModLoadimudp$UDPServerRun514# Provides TCP syslog reception$ModLoadimtcp$InputTCPServerRun514local2.* /var/log/haproxy.log[rootmaster.xulei.com ~]# systemctl restart rsyslog[rootmaster.xulei.com ~]# netstat -tunlp |grep :514tcp000.0.0.0:5140.0.0.0:* LISTEN2755/rsyslogd tcp00:::514 :::* LISTEN2755/rsyslogd udp000.0.0.0:5140.0.0.0:*2755/rsyslogd udp00:::514 :::*2755/rsyslogd[rootmaster.xulei.com ~]# tailf /var/log/haproxy.logJan1602:51:10 localhost haproxy[2734]:[16/Jan/2016:02:51:10.487]www.xulei.com www.xulei.com/http30/0/0/0/0200265- - ----1/1/0/1/00/0HEAD / HTTP/1.1Jan1602:51:15 localhost haproxy[2734]:[16/Jan/2016:02:51:15.493]www.xulei.com www.xulei.com/http10/0/0/1/1200265- - ----1/1/0/1/00/0HEAD / HTTP/1.1Jan1602:51:20 localhost haproxy[2734]:[16/Jan/2016:02:51:20.490]www.xulei.com www.xulei.com/http20/0/0/1/1200265- - ----1/1/0/1/00/0HEAD / HTTP/1.1主/备调度器 正常只有活跃的调度器发送组播[rootmaster.xulei.com ~]# tcpdump -i eth0 -nn vrrptcpdump: verbose output suppressed, use-vor-vvforfull protocol decode listening on eth0, link-type EN10MB(Ethernet), capture size65535bytes 02:13:38.483890 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:39.484731 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:40.487664 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:41.488244 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:42.489277 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:43.490422 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:44.491214 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:45.491975 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:46.492977 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length2002:13:47.494123 IP192.168.122.56224.0.0.18: VRRPv2, Advertisement, vrid88, prio100, authtype simple, intvl 1s, length204、Haproxy 实现四层负载Haproxy L4 global log 127.0.0.1 local2 chroot /var/lib/haproxy pidfile /var/run/haproxy.pid maxconn 4000 user haproxy group haproxy daemon defaults mode http log global option dontlognull retries 3 maxconn 3000 contimeout 50000 clitimeout 50000 srvtimeout 50000 listen stats bind *:1314 stats enable stats hide-version stats uri /haproxystats stats realm Haproxy\ stats stats auth qfedu:123 stats admin if TRUE frontend web option httplog option http-server-close option forwardfor except 127.0.0.0/8 #option redispatch mode http bind *:80 default_backend httpservers backend httpservers balance roundrobin server http1 192.168.122.10:80 check maxconn 2000 server http2 192.168.122.20:80 check maxconn 2000 server http3 192.168.122.30:80 check maxconn 2000 listen mysql bind *:3306 mode tcp balance roundrobin server mysql1 192.168.122.40:3306 weight 1 check inter 1s rise 2 fall 2 server mysql2 192.168.122.50:3306 weight 1 check inter 1s rise 2 fall 2 server mysql3 192.168.122.60:3306 weight 1 check inter 1s rise 2 fall 2 这2篇7层负载运维。围绕七层负载均衡展开先讲解 OSI 七层与 TCP/IP 四层网络模型完整演示 Nginx 同时配置 http 七层 upstream 负载和 stream 四层 TCP 负载的写法梳理轮询、加权轮询、ip_hash 等多种调度算法及 down、backup 等后端状态参数给出超时、故障重试配置解决后端服务宕机导致请求卡住的问题配套完整 Tomcat 多实例部署、Nginx 反向代理 Tomcat 集群实战流程接着介绍专业负载均衡 HAProxy讲解其性能、会话保持、8 种调度算法、http/tcp 两种工作模式拆解 global、defaults、frontend、backend、listen 五大配置模块并提供完整可运行配置示例还结合 Keepalived 实现 HAProxy 主备高可用架构同时演示日志收集、tcpdump 抓包排查等运维实操覆盖 Web 与数据库四层分流场景完整落地中小型到企业级流量分发高可用方案是一套兼顾理论、配置脚本与实操测试的七层负载均衡落地指南。