haproxy

作者本人也搭建了一个docker镜像加速器,需要的朋友随时联系作者,镜像加速嘎嘎快,快速解决docker镜像拉不下的问题,文章最后带有作者wx,先好好学习吧。

haproxy

一、haproxy安装

1.1 yum 安装

wget https://repo.ius.io/ius-release-el7.rpm
yum localinstall ius-release-el7.rpm 
yum --enablerepo=ius-testing install haproxy22

1.2 安装lua

由于centos自带的lua版本比较低并不符合HAProxy要求的lua最低版本(5.3.5)的要求,因此需要编译安装较新版本的lua环境,然后才能编译安装HAProxy,过程如下

[root@k8s-vip ~]# yum install -y libtermcap-devel ncurses-devel libevent-devel readline-devel   libsystemd-dev           
yum -y install pcre pcre-devel zlib zlib-devel gcc gcc-c++ glibc glibc-devel systemd-devel zip zlib-devel openssl openssl-devel wget
[root@k8s-vip src]# wget https://www.lua.org/ftp/lua-5.4.2.tar.gz

[root@k8s-vip src]# cd lua-5.4.2
[root@k8s-vip lua-5.4.2]# make all test

1.3 二进制安装

wget https://src.fedoraproject.org/repo/pkgs/haproxy/haproxy-2.2.13.tar.gz/sha512/33f0821b49e5916621d06cd524e25011072bfd0a9ed2db95a53c2d26f51ac484866fedbc54f2214b250f502297063926e6c5f6f4dee8aa77cde24098835c213d/haproxy-2.2.13.tar.gz

make ARCH=x86_64 TARGET=linux-glibc USE_OPENSSL=1 USE_PCRE=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 USE_LUA=1 LUA_INC=/usr/local/src/lua-5.4.2/src/ LUA_LIB=/usr/local/src/lua-5.4.2/src/ PREFIX=/apps/haproxy
make install PREFIX=/apps/haproxy

1.4 验证haproxy版本

[root@k8s-vip ~]# /apps/haproxy/sbin/haproxy -v
HA-Proxy version 2.2.13-5f3eb59 2021/04/02 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2025.
Known bugs: http://www.haproxy.org/bugs/bugs-2.2.13.html
Running on: Linux 3.10.0-1160.el7.x86_64 #1 SMP Mon Oct 19 16:18:59 UTC 2020 x86_64

1.5 haproxy启动脚本

 [root@k8s-vip ~]# cat/usr/lib/systemd/system/haproxy.service     
-bash: cat/usr/lib/systemd/system/haproxy.service: 没有那个文件或目录
[root@k8s-vip ~]# cat /usr/lib/systemd/system/haproxy.service 
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target

[Service]
ExecStartPre=/apps/haproxy/sbin/haproxy -f /etc/haproxy/haproxy.cfg  -c -q 
ExecStart=/apps/haproxy/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target

1.6 配置文件

[root@k8s-vip ~]# cat /etc/haproxy/haproxy.cfg    
global
        maxconn         10000
        chroot          /apps/haproxy
        stats socket    /var/lib/haproxy/haproxy.sock  mode 600 level admin
        log             127.0.0.1 local0
        uid             99
        gid             99
        daemon
        #nbproc 4
        #cpu-map 1 0
        #cpu-map 2 1
        #cpu-map 3 2
        #cpu-map 4 3
        pidfile /var/lib/haproxy/haproxy.pid
        log 127.0.0.1 local3 info 

defaults
        option http-keep-alive
        option forwardfor
        maxconn  10000
        mode http
        timeout connect         30s
        timeout client          30s
        timeout server          30s
listen stats 
        mode http
        bind 0.0.0.0:9999
        stats enable 
        log global
        stats uri /haproxy-status
        stats auth   gf:1234
listen web_port
   bind 0.0.0.0:80
   mode http
   log global
   server web1 172.16.10.51:80 check inter 3000 fall 2 rise 5

1.7启动haproxy

systemctl start haproxy


[root@k8s-vip ~]# systemctl status haproxy
● haproxy.service - HAProxy Load Balancer
   Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; vendor preset: disabled)
   Active: active (running) since 日 2024-01-14 12:08:30 CST; 57min ago
 Main PID: 1343 (haproxy)
   CGroup: /system.slice/haproxy.service
           ├─1343 /apps/haproxy/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
           └─1347 /apps/haproxy/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid

114 12:08:30 k8s-vip systemd[1]: Starting HAProxy Load Balancer...
114 12:08:30 k8s-vip systemd[1]: Started HAProxy Load Balancer.
114 12:08:30 k8s-vip haproxy[1343]: [NOTICE] 013/120830 (1343) : New worker #1 (1347) forked
114 12:08:33 k8s-vip haproxy[1343]: [WARNING] 013/120833 (1347) : Server web_port/web1 is DOWN, reason: L...ueue.
114 12:08:33 k8s-vip haproxy[1343]: [NOTICE] 013/120833 (1347) : haproxy version is 2.2.13-5f3eb59
114 12:08:33 k8s-vip haproxy[1343]: [NOTICE] 013/120833 (1347) : path to executable is /apps/haproxy/sbin/haproxy
114 12:08:33 k8s-vip haproxy[1343]: [ALERT] 013/120833 (1347) : proxy 'web_port' has no server available!
Hint: Some lines were ellipsized, use -l to show in full.

二:haproxy配置详解

2.1:基础配置详解

HAProxy的配置文件haproxy.cfg由两大部分组成,分别是global和proxies两部分

global:全局配置段

进程及安全配置相关的参数
性能调整相关参数
Debug参数

proxies:代理配置段

defaults: 为frontend,backend,listen提供默认配置
frontend:前端,相当于nginx中的server {}
backend: 后端,相当于nginx中的upstream {}
listen: 同时拥有前端和后端的配置
2.1.1: global配置参数
chroot #锁定运行目录
deamon #以守护进程运行
#stats socket    /var/lib/haproxy/haproxy.sock  mode 600 level admin #socket文件
user, group, uid, gid #运行haproxy的用户身份
nbproc #开启的haproxy进程数,与cpu保持一致
nbthread #指定每个haproxy进程开启的线程数,默认为每个进程一个线程
cpu-map 1 0 #绑定haproxy 进程至指定cpu,单进程多线程和多进程单线程不能并存
maxconn #每个haproxy进程的最大并发连接数
maxsslconn #每个haproxy进程ssl最大连接数,用于haproxy配置了证书的场景下
maxconnrate #每个进程每秒创建的最大连接数量
spread-checks #后端server状态check随机提前或延迟百分比时间,建议2-5(20%-50%)之间
pidfile #指定pid文件路径
log 127.0.0.1 local3 info #定义全局的syslog服务器,最多可以定义两个
cat /proc/1320/status 查看进程
2.1.2: proxies配置

https://cbonte.github.io/haproxy-dconv/2.0/configuration.html#2.1

defaults [<name>] #默认配置项,针对以下的frontend、backend和listen生效,可以多个name也可以没有name
frontend <name> #前端servername,类似于Nginx的一个虚拟主机 server
backend <name> #后端服务器组,等于nginx和upstream
listen <name> #将frontend和backend合并在一起配置

注:name字段使用"-" “_” “.” “:”,并且严格区分大小写,例如:Web和web是完全不同的两组服务器

2.1.2.1:Proxies配置-defaults:

defaults配置参数

option redispatch #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
option abortonclose #当服务器负载很高的时候,自动结束掉当前队列处理比较久的连接,关闭
option http-keep-alive #开启与客户端的会话保持
option forwardfor #透传客户端真实ip至后端web服务器
mode http #设置默认工作类型
timeout http-keep-alive 120s #session会话保持超时时间,范围内会转发到相同的后端服务器
timeout connect 120s #客户端请求从haproxy到后端server的最长连接等待时间(tcp之前)
timeout server 600s #客户端请求从haproxy到后端服务器的请求处理超时时长(tcp之后)
timeout client 600s #设置haproxy与客户端的最长非活动时间
timeout check 5s #对后端服务器的默认检测超时时间

在这里插入图片描述

2.1.2.2: proxies配置-frontend:
bind: 指定HAProxy的监听地址,可以是IPV4或IPV6,可以同时监听多个IP或端口,可同时用于listen字段中
bind [<address>]:<port_range> [, ...] [param*]

listen http_proxy #监听http的多个IP的多个端口和sock文件
    bind :80,:443
    bind 10.0.0.1:10080,10.0.0.1:10443
    bind /var/run/ssl-frontend.sock user root mode 600 accept-proxy

listen http_https_proxy #https监听
    bind :80
    bind :443 ssl crt /etc/haproxy/site.pem

listen http_https_proxy_explicit #监听ipv6、ipv4和unix sock文件
    bind ipv6@:80
    bind ipv4@public_ssl:443 ssl crt /etc/haproxy/site.pem
    bind unix@ssl-frontend.sock user root mode 600 accept-proxy

listen external_bind_app1 #监听file descriptor
    bind "fd@${FD_APP1}"

生产实例
listen web-port
	bind :80,:8080
	bind 192.168.7.102:10080,:8801-8810,192.168.7.101:9001-9010
	mode http/tcp #指定负载协议类型
	use_backend backend_name #调用的后端服务器组名称


2.1.2.3:proxies配置-backend:

定义一组后端服务器,backend服务器将被frontend进行调用

mode http/tcp #指定负载协议类型
option #配置选项
server #定义后端real server

注意:option后面加httpchk,smtpchk,mysql-check, pgsql-check, ssl-hello-chk方法,可用于实现更多应用层功能

check #对指定real进行健康状态检查,默认不开启
	addr IP #可指定的健康状态检测IP
	port num #指定的健康状态监测端口
	inter num #健康状态检测间隔时间,默认2000ms
	fall num #后端服务器失效检查次数,默认为3
	rise num #后端服务器从下线恢复检查次数,默认为2
weight #默认为1 ,最大值为256, 0表示不参与负载均衡
backup #将后端服务器标记为备份状态
disabled #将后端服务器标记为不可用状态
maxconn <maxconn>: 当前后端server的最大并发连接数
backlog <backlog>: 当server的连接数达到上限后的后源队列长度
2.1.2.4:frontend+backend配置实例
frontend web_port_http
   bind 172.16.10.105:80
   mode http
   use_backend web_port_http_backend

backend web_port_http_backend
   mode http
   option forwardfor
   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check inter 3000 fall 2 rise 5
2.1.2.5:proxies配置-listen替代frontend+backend:
listen apache_port
   bind 172.16.10.105:82
   mode http
   option forwardfor
   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check inter 3000 fall 2 rise 5
整体配置
[root@k8s-vip ~]# cat /etc/haproxy/haproxy.cfg 
global
        maxconn         10000
        chroot          /apps/haproxy
        stats socket    /var/lib/haproxy/haproxy.sock  mode 600 level admin
        log             127.0.0.1 local0
        uid             99
        gid             99
        daemon
        #nbthread 32 #开启多线程不能开多进程
        #nbproc 4
        #cpu-map 1 0
        #cpu-map 2 1
        #cpu-map 3 2
        #cpu-map 4 3
        pidfile /var/lib/haproxy/haproxy.pid
        log 127.0.0.1 local3 info 

defaults
        option http-keep-alive #开启与客户端的会话保持
        option forwardfor #透传客户端真实ip至后端web服务器
        option redispatch  #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
        option abortonclose #服务器负载很高的时候,自动结束掉当前队列处理比较久的连接,关闭
        maxconn  10000
        mode http
        timeout connect         30s #客户端请求从haproxy到后端server的最长连接等待时间(tcp之前)
        timeout client          30s #设置haproxy与客户端的最长非活动时间
        timeout server          30s #客户端请求从haproxy到后端服务器的请求处理超时时长(tcp之后)
        timeout http-keep-alive 120s  #session会话保持超时时间,范围内会转发到相同的后端服务器
        
listen stats 
        mode http
        bind 0.0.0.0:9999
        stats enable 
        log global
        stats uri /haproxy-status
        stats auth   gf:1234
listen web_port
   bind 172.16.10.105:8080
   bind 172.16.10.105:8020
   mode http
   log global
   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5



frontend web_port_http
   bind 172.16.10.105:80
   mode http
   use_backend web_port_http_backend

backend web_port_http_backend
   mode http
   option forwardfor
   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check inter 3000 fall 2 rise 5


listen apache_port
   bind  :8082-8810
   mode http
   option forwardfor
   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check addr 172.16.10.61 port 6379 inter 3000 fall 2 rise 5
   
   
listen redis-cli
   bind 172.16.10.105:6379
   mode tcp
   server redis 172.16.10.61:6379 check inter 3000 fall 2 rise 5

三:HAProxy调度算法:

HAProxy通过固定参数balance指明对后端服务器的调度算法,该参数可以配置在listen或backend选项中

HAProxy的调度算法分为静态和动态调度算法,但是由些算法也可以根据参数在静态和动态算法中相互转换

https://cbonte.github.io/haproxy-dconv/2.0/configuration.html#4 官方文档

3.1:静态算法

静态算法:按照事先定义好的规则轮询公平调度,不关心后端服务器的当前负载、链接数和响应速度等,且无法实现修改权重,只能靠重启HAProxy生效
服务器动态权重调整

# yum install socat #Socat 是linux下的一个多功能的网络工具,名字来由是Socket CAT,Socat的主要特点就是在两个数据流之间建立通道,且支持众多协议和连接方式。如IP、TCP、UDP、IPv6、Socket文件等。
# echo "show info " | socat stdio /var/lib/haproxy/haproxy.sock
[root@k8s-vip ~]# echo "get weight web_port/web1" | socat stdio /var/lib/haproxy/haproxy.sock            
1 (initial 1)

[root@k8s-vip ~]# echo "set  weight web_port/web1 2" | socat stdio /var/lib/haproxy/haproxy.sock 
3.1.1: static-rr:

static-rr:基于权重的轮询调度,不支持权重的运行时调整及后端服务器慢启动(慢慢分配流量,不会把流量直接打满),其后端主机数量没有限制

listen apache_port
   bind  :8082-8810
   mode http
   balance static-rr
   option forwardfor
   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check addr 172.16.10.61 port 6379 inter 3000 fall 2 rise 5
3.1.2: first

first: 根据服务器在列表中的位置,自上而下的进行调度,但是其只会当第一台服务器的连接数达到上限,新请求才会分配给下一台服务,因此会忽略服务器的权重设置


listen apache_port
   bind  :8082-8810
   mode http
   balance static-rr
   option forwardfor
   server web1 172.16.10.50:80 check maxconn 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check addr 172.16.10.61 port 6379 inter 3000 fall 2 rise 5

测试访问效果

while true; do curl 172.16.10.105:8083;sleep 0.2s ;done

3.2:动态算法

动态算法:基于后端服务器状态进行调度适当调整,比如优先调度至当前负载较低的服务器,且权重可以在haproxy运行时动态调整无需重启

3.2.1:roundrobin:

roundrobin:基于权重的轮询动态调度算法,支持权重的运行时调整,不完全等于lvs中的rr轮询模式,HAProxy中的roundrobin支持慢启动(新加的服务器会逐渐增加转发数),其每个后端backend中最多支持4095个real server,roundrobin为默认调度算法,且支持对real server权重动态调整

listen apache_port
   bind  :8082-8810
   mode http
   balance roundrobin
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5

动态调整权限:

echo "set weight apache_port/web1 3" | socat stdio /var/lib/haproxy/haproxy.sock

echo "get weight apache_port/web1" | socat stdio /var/lib/haproxy/haproxy.sock

3.2.2: leastconn

leastconn加权的最少连接的动态,支持权重的运行时调整和慢启动,即当前后端服务器连接最少的优先调度(新客户连接),比较适合长连接的场景是哟个,比如Mysql等场景

listen apache_port
   bind  :8082-8810
   mode http
   balance leastconn
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5

3.3: 其他算法:

其他算法即可作为静态算法,又可以通过选项成为动态算法

3.3.1:source:

源地址hash,基于用户源地址hash并将请求转发到后端服务器,默认为静态即取模方式,但是可以通过hash-type支持的选项更改,后续统一个源地址请求将转发到同一个后端服务器,比较适用于session保持/缓存业务等场景。

源地址有两种转发客户端请求到后端服务器的服务器选取计算方式,分别是取模发和一致性hash

3.3.1.1:map-base取模法:
map-based: 取模法,基于服务器总权重的hash数组取模,该hash是静态的既不支持在线调整权重,不支持慢启动,其对后端服务器调度均衡,缺点是当服务器的总权重发生变化时,既有服务器上线和下线,都会因权重发生变化而导致调度结果整体改变。
所谓取模运算,就是计算两个数相除之后的余数,10%7=3,7%4=3,基于权重取模:(2^32-1)%(1+1+2),公式为hash(o) mod n,即a mod b =c,表明a除以b余数为c。
取模法原理:客户端请求到达haproxy,haproxy会对源地址就行hash(公网地址不用源地址hash,因为ip是一个家庭,公司),haproxy加载配置文件,读取real server的权重,权重相加,例,总权重为3 ,取模不会大于3,取模结果0,1,2,对应三台服务器(haproxy维护一张表,起来之后会记录每个服务器的权重)。

在这里插入图片描述

3.3.1.1.2:取模法配置示例:
listen apache_port
   bind  :8082-8810
   mode http
   balance source
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.1.2:一致性hash:

一致性hash,该hash时动态的,支持在线调整权重,支持慢启动,优点在于当服务器的总权重发生变化时,对调度结果影响是局部的,不会引起大的变动

3.3.1.2.1:hash对象:

Hash对象到后端服务器的映射关系

在这里插入图片描述

对地址(用户请求报文都可以hash)进行hash,hash出来的结果会落到一个范围,每个服务器对应一个范围,hash完不会落到服务器上,没有服务器会顺延。服务器down,也会顺延

在这里插入图片描述

3.3.1.2.2 :一致性hash配置实例:
listen apache_port
   bind  :8082-8810
   mode http
   balance source
   hash-type consistent #加上这静态转动态
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.2:uri:

基于对用户请求的uri做hash并将请求转发到后端指定服务器,也可以通过map-based和connsistent定义取模法还是一致性hash。

http://www.gf.com/images/1.jpg   #URI/URL
ftp://gf.cn/1.jpg  #URI/URL
/images/1.png  #URI

在这里插入图片描述

3.3.2.1: uri取模法配置实例:
listen apache_port
   bind  :8082-8810
   mode http
   balance uri
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.2.2: uri一致性hash配置实例:
listen apache_port
   bind  :8082-8810
   mode http
   balance uri
   hash-type consistent
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.3:url_param:

url_param对用户请求的url中的params部分中的参数name作hash计算,并由服务器总权重相除以后派发给某挑出的服务器,通常用于追踪用户,以确保来自同一个用户的请求始终发往同一个real server

假设url = http://www.gf.com/foo/bar/index.html?k1=v1&k2=v2

host = www.gf.com
url_param = k1=v1&k2=v2
3.3.3.1:url_param取模法配置实例:
listen apache_port
   bind  :8082-8810
   mode http
   balance url_param name
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5

http://172.16.10.105:8083/?name=gf

3.3.3.2:url_param一致性hash配置示例:
listen apache_port
   bind  :8082-8810
   mode httpbash
   balance url_param name
   hash-type consistent
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.4:hdr:

针对用户每个http头部(header)请求中的指定信息做hash,此处有name指定的http首部将会被取出并做hash计算,然后由服务器总权重相除以后派发至某挑出的服务器,假如无有效的值,则会使用默认的轮询调度

3.3.4.1:hdr取模法配置实例
listen apache_port
   bind  :8082-8810
   mode http
   balance hdr(User-Agent)
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.4.2: hdr一致性hash配置示例
listen apache_port
   bind  :8082-8810
   mode http
   hash-type consistent
   balance hdr(User-Agent)
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.5:rdp-cookie

rdp-cookie可以实现对windows远程桌面的负载,如果有多个后端windows server服务器,rdp-cookie可以实现同一个windows server的请求始终被转发给同一个服务器,如果之前从未访问过,那么第一次使用连接roundrobin算法计算出一个后端服务器并进行转发

3.3.5.1:rdp-cookie取模法配置示例
listen rdp-cookie
   bind  172.16.10.105:3389
   mode tcp
   balance rdp-cookie
   option forwardfor
   server web1 172.16.10.50:3389 check weight 1 inter 3000 fall 2 rise 5
3.3.5.2:rdp-cookie一致性hash配置示例
listen rdp-cookie
   bind  :8082-8810
   mode http
   persist rdp-cookie #启用基于RDP cookie的持久连接,同一个cookie就转发给对应得服务器。
   tcp-request inspect-delay 5s #设置内容检查期间等待数据得最大永许时间
   tcp-request content accept if RDP_COOKIE #配置RDP_COOKIE存在就接受请求
   balance rdp-cookie
   option forwardfor
   # hash-type consistent
   server web1 172.16.10.50:3389 check weight 1 inter 3000 fall 2 rise 5
3.3.5.3:iptable实现

sysctl -a #开启内核转发

vim /etc/sysctl.conf 
net.ipv4.ip_forward = 1

iptables -t nat -A PREROUTING -d 172.16.33.50(haproxy地址) -p tcp --dport 3389 -j DNAT --to-destination 172.16.33.0/24

iptables -t nat -A POSTROUTING -s 172.16.33.0/24 -j SNAT --to-source 172.16.33.50

3.3.6:random:

在1.9版本开始增加一个叫做random得负载均衡算法,其基于一个随机数作为一致性hash得key,随机负载均衡对于大型服务器场或经常添加或删除服务器非常有用。

3.3.6.1:random配置实例
listen apache_port
   bind  :8082-8810
   mode http
   balance random
   option forwardfor
   server web1 172.16.10.50:80 check weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check weight 2 inter 3000 fall 2 rise 5
3.3.7:算法总结:
static-rr ---------->tcp/http 静态
first--------------->tcp/http 静态

roundrobin---------->tcp/http 动态
leastconn----------->tcp/http 动态
random ------------->tcp/http 动态

source-------------->tcp/http 
uri----------------->http
url_param----------->http         取绝于hash_type是否consistent
hdr----------------->http
rdp-cookie---------->tcp
3.3.8:各算法使用场景
first #使用较少

static-rr #做了session共享得集群
roundrobin
random

leastconn #数据库
source #基于客户端公网ip得会话保持

uri----------->http  #缓存服务器,CDN服务商、百度、阿里云
url_param------>http

hdr #基于客户端请求报文头部做下一步处理

rdp-cookie #很少使用
3.3.9:layer 4与layer 7:

四层:IP+PORT转发

七层:协议+内容交换

在这里插入图片描述

3.3.9.1:四层负载

在四层负载设备中,把client发送得报文目标地址(原来是负载均衡设备得ip地址),根据均衡设备设置的原则web服务器得规则选择对应得web服务器ip地址,这样client就可以直接根此服务器建立tcp连接并发送数据

3.3.9.2:七层代理:

七层负载均衡服务器起了一个反向代理服务器得作用,服务器建立一次tcp连接要三次握手,而client要访问webserver要先与七层负载设备进行三次握手后建立tcp连接,把要访问得报文信息发送给七层负载均衡;然后七层负载均衡在根据设置得均衡规则选择特定得webserver,然后通过三次握手与此台webserver建立tcp连接,然后webserver把需要得数据发送给七层负载均衡设备,负载均衡设备再把数据发送给client;所以,七层负载均衡起到了代理服务器得作用

tcpdump tcp -i eth0 -nn port ! 22 -w dump-tcp.pacp -v

3.4:IP透传:

web服务器中需要记录客户端的真实ip地址,用于做访问统计、安全防护、行为分析、区域排行等场景

3.4.1:四层ip透传
listen apache_port
   bind  :8082-8810
   mode tcp
   server web1 172.16.10.50:80 check send-proxy  weight 1 inter 3000 fall 2 rise 5
   
   
   server {
   listen 80 proxy_protocol;
   server_name 172.16.10.50;
   access_log /var/nginx/logs/gggg.gf.com-access.log access_json;
   location / {
       root /data/nginx;
       index index.html;
   }
}


$proxy_protocol_addr 获取真实ip地址
3.4.2:七层ip透传

当haproxy工作在七层的时候,如何透传客户端真实ip至后端服务器

3.4.2.1:haproxy配置
defaults 
option forwardfor 

或者:
    option forwardfor header X-Forwarded-xxx#自定义传递IP参数,后端web服务器写X-Forwarded-xxx,如果写option forwardfor则后端服务器web格式为X-Forwarded-For
    
    
    
    listen apache_port
   bind  :8082-8810
   mode http
   option forwardfor
   server web1 172.16.10.50:80 check   weight 1 inter 3000 fall 2 rise 5

3.4.2.2:web服务器日志格式配置

配置web服务器,记录负载均衡透传的客户端ip地址

apache配置
LogFormat "\"%{X-Forwarded-For}i\"  %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

#tomcat配置
pattern= %{X-Forwarded-For}i

#nginx配置
'"xff":"$http_x_forwarded_for",'

四:高级功能及配置:

介绍HAProxy高级配置及使用案例

4.1:基于cookie的会话保持

cookie value:为当前server指定cookie值,实现基于cookie的会话黏性

4.1.1:配置选项
cookie <name> [ rewrite | insert | prefix ] [ indirect ] [ nocache ]
              [ postonly ] [ preserve ] [ httponly ] [ secure ]
              [ domain <domain> ]* [ maxidle <idle> ] [ maxlife <life> ]
              [ dynamic ] [ attr <value> ]*
              
    name:cookie的key名称,用于实现持久连接
    insert: 如果客户端请求报文没有cookie就插入新的cookie到响应报文,如第一次访问HAProxy
    indirect:不会向客户端发送服务器已经修理过请求的cookie信息,比如后端服务器宕机后HAProxy将客户端请求强制转发至real server则会涉及修改cookie,不建议配置。(修改过cookie要告诉客户端)
    nocache: #当client和haproxy之间有缓存时,haproxy不缓存客户端cookie,因为客户端浏览器会缓存cookie并携带cookie访问haproxy 
4.1.2:配置示例
listen apache_port
   bind  :8082-8810
   mode http
   option forwardfor
   cookie server-cookie insert nocache
   server web1 172.16.10.50:80 check  cookie web1  weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5

通过命令行指定cookie

curl --cookie "server-cookie=web1" 172.16.10.105:8083/index.html

4.2:HAProxy状态页

4.2.1:状态页配置项:
stats enable #基于默认的参数启用stats page
stats hide-version #隐藏版本
stats refresh <delay> #设定自动刷新时间间隔
stats uri <prefix> #自定义stats page uri,默认值:/haproxy?stats
stats realm <realm> #账户认证时的提示信息,示例:stats realm :HAProxy\ Statistics
stats auth <user>:<passwd> #认证时的账号和密码,可使用多次,默认:no authentication
stats admin {if | unless} <cond> #启用stats page 中的管理功能
4.2.2:启用状态页:
listen stats
        mode http
        bind 0.0.0.0:9999
        stats enable
        log global
        stats uri /haproxy-status
        stats auth   gf:1234
        stats hide-version
        stats realm Haproxy\ statistics
        stats admin if TRUE
        stats refresh 3s
4.2.3:登录状态页
pid = 1363 (process #2, nbproc = 4, nbthread = 1) #pid为当前pid号,process为当前进程号,nbproc和nbthread为一共多少进程和每个进程多少线程
uptime = 0d 0h01m02s #启动了多长时间
system limits: memmax = unlimited; ulimit-n = 20766 #系统资源限制:内存/最大打开文件数
maxsock = 20766; maxconn = 10000; maxpipes = 0#最大socket连接数/单进程最大连接数/最大管道数maxpipes
current conns = 1; current pipes = 0/0; conn rate = 0/sec; bit rate = 0.000 kbps#当前连接数/当前管道数/当前连接速率
Running tasks: 1/16; idle = 100 %#运行的任务/当前空闲率
active UP #在线服务器
backup UP #标记为backup的服务器
active UP, going down #监测未通过正在进入down的过程
backup UP, going down #备份服务器正在进入down的过程
active DOWN, going up #down的服务器正在进入up过程	
backup DOWN, going up #备份服务器正在进入up过程
active or backup DOWN #在线的服务器或者是backup的服务器已经转换成了down状态  	
not checked #标记为不监测的服务器
active or backup DOWN for maintenance (MAINT)   #active或者backup服务器为下线的
active or backup SOFT STOPPED for maintenance   #active或者backup被任为软下线(人为将weight改为0)

免密钥登录

ssh-keygen 
ssh 172.16.10.105
# 动态修改权重
[root@dl ~]# ssh root@172.16.10.105  'echo "get weight apache_port/web1 " | socat stdio /var/lib/haproxy/haproxy.sock' 
4 (initial 1)
4.2.4:backend server信息:
session rate(每秒的连接会话信息)Errors(错误统计信息)
cur:每秒的当前会话数量Req:错误请求量
max:每秒新的最大会话数量conn:错误链接量
limit:每秒新的会话限制量Resp:错误响应量
sessions(会话信息):Warnings(警告统计信息)
cur:当前会话量Retr:重新尝试次数
max:最大会话量Redis:再次发送次数
limit:限制会话量
Total:总共会话量Server(real server信息)
LBTot:选中一台服务器所用的总时间Status:后端机的状态,包括UP和DOWN
Last:和服务器的持续连接时间LastChk:持续检查后端服务器的时间
Wght:权重
Bytes(流量统计)Act:活动链接数量
In:网络的字节输入总量Bck:备份的服务器数量
Out:网络的字节输出总量Chk:心跳检查时间
Dwn:后端服务器连接后都是DOWN的数量
Denied(拒绝统计信息)Dwntme:总的downtime时间
Req:拒绝请求量Thrtle:server状态
Resp:拒绝回复量

4.3:报文修改

在http模式下,基于实际需求修改客户端的请求报文与响应报文,通过reqadd和reqdel在请求报文添加删除字段,通过rspadd与rspidel在响应报文中添加与删除字段

在请求报文尾部添加指定首部
http-request add-header <string> [{if | unless} <cond>]

从请求报文中删除匹配正则表达式的首部
http-request del-header <search> [{if | unless} <cond>]
http-request del-header <search> [{if | unless} <cond>]

在响应报文尾部添加指定首部
http-response add-header <string> [{if | unless} <cond> ]
示例:
	http-response add-header X-Via:\ HAProxy

从响应报文中删除匹配正则表达式的首部
http-response del-header <search> [{if | unless} <cond>]

示例:
	http-response del-header server.* #从响应报文删除server信息
	http-response del-header X-Powered-By:.* #从响应报文删除X-Powered-By信息

4.4:HAProxy日志配置:

配置haproxy记录日志到指定文件中

4.4.1:haproxy配置:
在 global配置项定义:
log 127.0.0.1 local{1-7} info #基于syslog记录日志到指定设备,级别有(err、warning、info、debug)

listen web_port
   bind 172.16.10.105:8080
   bind 172.16.10.105:8020
   mode http
   log global
   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5
4.4.2:Rsyslog配置
vim /etc/rsyslog.conf 
$ModLoad imudp
$UDPServerRun 514
local3.*                 /var/log/haproxy.log

systemctl restart rsyslog

4.5:自定义日志格式

将特定信息记录在日志中

4.5.1:配置选项
capture cookie <name> len <length> #捕获请求和响应报文中cookie并记录日志
capture request header <name> len <length> #捕获请求报文中指定的首部内容和长度并记录日志
capture response header <name> len <length> #捕获响应报文中指定的内容和长度首部并记录日志
	示例:
   capture request header Host len 32
   capture response header Server len 32
4.5.2配置实例
listen web_port
   bind 172.16.10.105:8080
   bind 172.16.10.105:8020
   mode http
   log global
   option httplog #日志格式选项
   capture request header Host len 32
   capture response header Server len 32

   server web1 172.16.10.50:80 check inter 3000 fall 2 rise 5

4.6:压缩功能

对响应给客户端的报文进行压缩,以节省网络带宽,但是会占用部分cpu性能

4.6.1:配置选项:
commpression algo #启用HTTP协议中的压缩机制,常用算法有gzip deflate
	identity	#调试使用的压缩方式
	gzip #常见的压缩方式,与各浏览器兼容较好
	deflate #有些浏览器不支持
	raw-deflate #新出的压缩方式
compression type #要压缩的文件类型
4.6.2:配置实例
listen apache_port
   bind  :8082-8810
   mode http
   option forwardfor
   cookie server-cookie insert nocache
   log global
   option httplog
   compression algo gzip deflate
   compression type text/plain text/html text/css text/xml text/javascript application/javascript
   server web1 172.16.10.50:80 check  cookie web1  weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5

4.7:web服务器状态监测:

基于不同的监测方式,对后端real server进行状态监测

option httpchk
option httpchk <uri>
option httpchk <method> <uri>
option httpchk <method> <uri> <version>
4.7.1:三种状态监测方式
基于四层的传输端口做状态监测

基于指定URI做状态监测

基于指定URI的request请求头部内容做状态监测
4.7.2:配置实例
listen apache_port
   bind  :8082-8810
   mode http
   option forwardfor
   cookie server-cookie insert nocache
   log global
   option httplog
   #option httpchk GET /web/index.html
   #option httpchk GET /web/index.html HTTP/1.0
   option httpchk GET /web/index.html HTTP/1.0\r\nHost:\ 172.16.10.50(通过源地址监测)

   server web1 172.16.10.50:80 check  cookie web1  weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5

4.8:ACL

访问控制列表(ACL,Access Control Lists)是一种基于包过滤的访问控制技术,它可以根据设定的条件对经过服务器传输的数据包进行过滤(条件匹配),及对接收到的报文进行匹配和过滤,基于请求报文头部中的源地址、源端口、目标端口、请求方法、URL、文件后缀等信息内容进行匹配并执行进一步操作,比如永许其通过或丢弃

4.8.1:ACL配置选项
acl   <aclname>    <criterion>   [flags]   [operator]  <value> 
acl    名称          匹配规范       匹配模式    具体操作符   操作对象类型
4.8.1.1:ACL-Name:
acl image_service  hdr_dom(host) -i img.magedu.com
ACL名称,可以使用大写字母A-Z、数字0-9、冒号:、点.、中横线和下划线,并且严格区分大小写,比如Image_site和image_site就是两个完全不同的acl。
4.8.1.2:ACL-criterion:

定义ACL匹配规范

hdr ([<name> [,<occ>]]): 完全匹配字符串,header的指定信息
hdr_beg  ([<name> [,<occ>]]):前缀匹配,header中指定内容的begin
hdr_end  ([<name> [,<occ>]]):后缀匹配,header中指定内容end
hdr_dom  ([<name> [,<occ>]]):域匹配,header中的domain name

hdr_dir   ([<name> [,<occ>]]):路径匹配,header的uri路径
hdr_len   ([<name> [,<occ>]]):长度匹配,header的长度匹配
hdr_reg   ([<name> [,<occ>]]):正则表达式匹配,自定义表达式(regex)模糊匹配
hdr_sub   ([<name> [,<occ>]]):字串匹配,header中的uri模糊匹配

dst   目标IP
dst_port 目标PORT

src 源IP
src_port 源PORT


实例:
	hdr(<string>)用于测试请求头部首部指定内容
	hdr_dom(host)请求的host名称,如www.magedu.com
	hdr_beg(host)请求的host开头,如www、img、vedio、download、ftp
	hdr_end(host)请求的host结尾,如 .com  .net  .cn
	path_beg 请求的URL开头,如/static、/images、/img、/css
	path_end 请求的URL中资源的结尾,如 .gif  .png  .css .js  .jpg  .jpeg
	
有些功能是类似的,比如以下几个都是匹配用户请求报文中host的开头是不是www
	acl  short_form  hdr_beg(host)          www.
	acl  alternate1  hdr_beg(host)  -m beg  www.
	acl  alternate2  hdr_dom(host)  -m beg  www.
	acl  laternate3  hdr(host)      -m beg  www.
	                                -m(使用正则表达式匹配)
4.8.1.3:ACL-flags:

ACL匹配模式

	-i 不区分大小写
	-m 使用指定的pattern(正则)匹配方法
	-n 不做dns解析
	-u 禁止acl重名,否则多个同名ACL匹配或关系
4.8.1.4:ACL-operator:

ACL操作符

整数比较:eq、ge、gt、le、lt
字符比较:
- exact match      (-m str):字符串必须完全匹配模式
- substring match  (-m sub):在提取的字符串中查找模式,如果其中任何一个被发现,ACL将匹配
- prefix match     (-m beg):在提取的字符串首部中查找模式,如果其中任何一个被发现,ACL进行匹配
- suffix match     (-m end):将模式与提取的字符串的尾部进行比较,如果其中任何一个匹配,则ACL进行匹配
- subdir match     (-m dir):查看提取出来的用斜线分割("/")的字符串,如果其中任何一个匹配,则ACL进行匹配
- domain match     (-m dom):查找提取的用点(".")分割字符串,如果其中任何一个匹配,则ACL进行匹配
4.8.1.5:ACL-value

value的类型

The ACL engine can match these types against patterns of the following types:
- Boolean #布尔值
- integer or integer range #整数或整数范围,比如用于匹配端口范围
- IP address / network #IP地址或IP范围,192.168.0.1,192.168.0.1/24
- string --> www.baidu.com
  exact      精确比较
  substring  子串
  suffix     后缀比较
  prefix     前缀比较
  subdir     路径        /wp-includes/js/jqurey/1.js
  domain     域名        www.magedu.com
- regular    expression   #正则表达式
- hex        block       #16进制
4.8.2:ACL调用方式

ACL调用方式

- 与:隐式(默认)使用
- 或:使用"or""||"表示
- 否定:使用"!"表示

示例:
	if valid_src   valid_port   #与关系,A和B都要满足为true
	if invalid_src  || invalid_port #或,A或者B满足一个为true
	if ! invalid_src  #非,取反,A和B那个也不满足为true
4.8.3:ACL示例-域名匹配
frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
   acl web_host  hdr_dom(host) -i www.gf.com
   #########################Backend setting###########################
   use_backend web_host_backend if web_host
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   backend web_host_backend
       mode http
       server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5
4.8.4:ACL示例-基于源IP或子网调度访问:

将指定的源地址调度至指定的web服务器组

frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
   acl ip_range  src 172.16.10.200 172.16.10.0/24
   #########################Backend setting###########################
   use_backend ip_range_backend if ip_range
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   backend ip_range_backend
       mode http
       server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5
4.8.5:ACL示例-基于源地址的访问控制(block):

frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
    acl web_host  hdr_dom(host) -i www.gf.com
   #########################Backend setting###########################
   block if web_host 
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   backend ip_range_backend
       mode http
       server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5
4.8.6:ACL示例-匹配浏览器类型:

匹配客户端浏览器,将不同类型的浏览器调动至不同的服务器组

   frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
    acl web_server_pattern  hdr_beg(User-Agent) -m sub "Mozilla"
   redirect prefix http://172.16.10.50:80  if web_server_pattern
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
4.8.7:ACL示例-基于文件后缀名实现动静分离
   frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
   acl image_server path_end -i .gif .jpg .png .js

   redirect prefix http://172.16.10.50:80  if image_server
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
       
 
   
   frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
   acl image_server path_end -i .gif .jpg .png .js
   use_backend  image_server_backend if image_server
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5     
    backend image_server_backend
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5  
4.8.8:ACL-匹配访问路径实现动静分离
   acl image_server path_beg -i /static  /js
   #acl web_server_pattern  hdr_beg(User-Agent) -m sub "Mozilla"
   redirect prefix http://172.16.10.50:80  if image_server
   
   
      frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
    acl image_server path_beg -i /static  /js
   use_backend  image_server_backend if image_server
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5     
    backend image_server_backend
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5  
4.8.9:ACL示例-基于ACL的HTTP访问控制:

frontend/listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   #########################ACL setting################################
    acl web_host  hdr_dom(host) -i www.gf.com
   #########################Backend setting###########################
   http-request deny if web_host
   #########################default server#####################
   default_backend default_web
   
   backend default_web
       mode http
       server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   backend ip_range_backend
       mode http
       server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5
4.8.10:ACL示例-预定义ACL使用

https://cbonte.github.io/haproxy-dconv/2.0/configuration.html#7.4

4.8.10.1:预定义的ACL
ACL nameEquivalent toUsage
FALSEalways_falsenever match
HTTPreq_proto_httpmatch if protocol is valid HTTP
HTTP_1.0req_ver 1.0match HTTP version 1.0
HTTP_1.1req_ver 1.1match HTTP version 1.1
HTTP_CONTENThdr_val(content-length) gt 0match an existing content-length
HTTP_URL_ABSurl_reg [/:]*😕/match absolute URL with scheme
HTTP_URL_SLASHurl_beg /match URL beginning with “/”
HTTP_URL_STARurl *match URL equal to “*”
LOCALHOSTsrc 127.0.0.1/8match connection from local host
METH_CONNECTmethod CONNECTmatch HTTP CONNECT method
METH_DELETEmethod DELETEmatch HTTP DELETE method
METH_GETmethod GET HEADmatch HTTP GET or HEAD method
METH_HEADmethod HEADmatch HTTP HEAD method
METH_OPTIONSmethod OPTIONSmatch HTTP OPTIONS method
METH_POSTmethod POSTmatch HTTP POST method
METH_PUTmethod PUTmatch HTTP PUT method
METH_TRACEmethod TRACEmatch HTTP TRACE method
RDP_COOKIEreq_rdp_cookie_cnt gt 0match presence of an RDP cookie
REQ_CONTENTreq_len gt 0match data in the request buffer
TRUEalways_truealways match
WAIT_ENDwait_endwait for end of content analysis
listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   acl web_host  hdr_dom(host) -i www.gf.com
   use_backend web_host_backend if web_host METH_POST
   
   backend default_web
      mode http
      server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5

   backend web_host_backend
       mode http
       server web2 172.16.10.61:80 check  cookie web2  weight 2 inter 3000 fall 2 rise 5

4.9:自定义HAProxy错误页面:

对指定的报错进行重定向,进行优雅的显示错误页面

4.9.1:基于错误页面文件

defaults
        option http-keep-alive #开启与客户端的会话保持
        option forwardfor #透传客户端真实ip至后端web服务器
        option redispatch  #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
        option abortonclose #服务器负载很高的时候,自动结束掉当前队列处理比较久的连接,关闭
        maxconn  10000
        mode http
        timeout connect         30s #客户端请求从haproxy到后端server的最长连接等待时间(tcp之前)
        timeout client          30s #设置haproxy与客户端的最长非活动时间
        timeout server          30s #客户端请求从haproxy到后端服务器的请求处理超时时长(tcp之后)
        timeout http-keep-alive 120s  #session会话保持超时时间,范围内会转发到相同的后端服务器
        log global
        errorfile 500 /usr/share/nginx/html/500.http
        errorfile 502 /usr/share/nginx/html/502.http
        errorfile 503 /usr/share/nginx/html/503.http

错误网页格式
HTTP/1.0 500 Internal Server Error
Cache-Control: no-cache
Connection: close
Content-Type: text/html
x-err-type: errors-1


<h1>错误</h1>
~                     
4.9.2:基于http重定向:

defaults
        option http-keep-alive #开启与客户端的会话保持
        option forwardfor #透传客户端真实ip至后端web服务器
        option redispatch  #当server Id对应的服务器挂掉后,强制定向到其他健康的服务器,重新派发
        option abortonclose #服务器负载很高的时候,自动结束掉当前队列处理比较久的连接,关闭
        maxconn  10000
        mode http
        timeout connect         30s #客户端请求从haproxy到后端server的最长连接等待时间(tcp之前)
        timeout client          30s #设置haproxy与客户端的最长非活动时间
        timeout server          30s #客户端请求从haproxy到后端服务器的请求处理超时时长(tcp之后)
        timeout http-keep-alive 120s  #session会话保持超时时间,范围内会转发到相同的后端服务器
        log global

        errorfile 503 http://172.16.10.50/error_page/503.html

4.10:HAProxy四层负载

针对有特殊访问负载的应用场景

Memcache
Redis
MySQL
RabbitMQ
4.10.1:四层负载示例:
listen redis-cli
   bind 172.16.10.105:6379
   mode tcp
   server redis 172.16.10.61:6379 check inter 3000 fall 2 rise 5
4.10.2:ACL示例-四层访问控制:

   listen web_port_http
   bind 172.16.10.105:80
   mode http
   option httplog
   log global
   acl web_host  hdr_dom(host) -i www.gf.com
   tcp-request connection reject if web_host
   
   backend default_web
      mode http
      server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5

4.11:haproxy https实现:

配置HAProxy支持https协议:
支持ssl会话
	bind *.443 ssl crt /PATH/TO/SOME_PEM_FILE
	crt 后证数问价为PEM格式,且同时包含证书和所有私钥
		cat demo.crt demo.key > demo.pem
把80端口的请求重定向443
	bind *:80
	redirct scheme https if !{ ssl_fc }
向后端传递用户请求的协议和端口(frontend 或 backend)
	http_request set-header X-Forwarded-Port %[dst_port]
	http_request add-header X-Forwarded-Proto https if { ssl_fc }
4.11.1:制作证书
mkdir /usr/local/haporxy/certs -p
cd /usr/local/haporxy/certs
openssl genrsa -out haproxy.key 2048
openssl req -new -x509 -key haproxy.key -out haporxy.crt -subj "/CN=www.gf.com"
cat haporxy.crt haproxy.key > haproxy.pem
openssl x509 -in haproxy.pem -noout -text #查看证书
chmod 600 haproxy.pem
listen web_port
   bind :80
   mode http
   option httplog
   log global
   redirect scheme https if !{ ssl_fc }
   server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check  weight 2 inter 3000 fall 2 rise 5

listen web_port_http
   #bind 172.16.10.105:443 crt /etc/haproxy/haproxy.pem
   bind :443 ssl crt /usr/local/haporxy/certs/haproxy.pem
   mode http
   option httplog
   log global
   server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check  weight 2 inter 3000 fall 2 rise 5

查看内核版本 uname -a cat /proc/version

查看cpu lscpu

netstat -antup 出现timeout怎么回事

大量的 TIME_WAIT 状态 TCP 连接存在,其本质原因是什么?

1.大量的短连接存在

2.特别是 HTTP 请求中,如果 connection 头部取值被设置为 close 时,基本都由「服务端」发起主动关闭连接

3.而,TCP 四次挥手关闭连接机制中,为了保证 ACK 重发和丢弃延迟数据,设置 time_wait 为 2 倍的 MSL(报文最大存活时间)

TIME_WAIT 状态:

1.TCP 连接中,主动关闭连接的一方出现的状态;(收到 FIN 命令,进入 TIME_WAIT 状态,并返回 ACK 命令)
2.保持 2 个 MSL 时间,即,4 分钟;(MSL 为 2 分钟)

nginx优化,算法

把80端口的请求重定向443
bind *:80
redirct scheme https if !{ ssl_fc }
向后端传递用户请求的协议和端口(frontend 或 backend)
http_request set-header X-Forwarded-Port %[dst_port]
http_request add-header X-Forwarded-Proto https if { ssl_fc }


#### 4.11.1:制作证书

```bash
mkdir /usr/local/haporxy/certs -p
cd /usr/local/haporxy/certs
openssl genrsa -out haproxy.key 2048
openssl req -new -x509 -key haproxy.key -out haporxy.crt -subj "/CN=www.gf.com"
cat haporxy.crt haproxy.key > haproxy.pem
openssl x509 -in haproxy.pem -noout -text #查看证书
chmod 600 haproxy.pem
listen web_port
   bind :80
   mode http
   option httplog
   log global
   redirect scheme https if !{ ssl_fc }
   server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check  weight 2 inter 3000 fall 2 rise 5

listen web_port_http
   #bind 172.16.10.105:443 crt /etc/haproxy/haproxy.pem
   bind :443 ssl crt /usr/local/haporxy/certs/haproxy.pem
   mode http
   option httplog
   log global
   server web1 172.16.10.50:80 check  weight 1 inter 3000 fall 2 rise 5
   server web2 172.16.10.61:80 check  weight 2 inter 3000 fall 2 rise 5

查看内核版本 uname -a cat /proc/version

查看cpu lscpu

netstat -antup 出现timeout怎么回事

大量的 TIME_WAIT 状态 TCP 连接存在,其本质原因是什么?

1.大量的短连接存在

2.特别是 HTTP 请求中,如果 connection 头部取值被设置为 close 时,基本都由「服务端」发起主动关闭连接

3.而,TCP 四次挥手关闭连接机制中,为了保证 ACK 重发和丢弃延迟数据,设置 time_wait 为 2 倍的 MSL(报文最大存活时间)

TIME_WAIT 状态:

1.TCP 连接中,主动关闭连接的一方出现的状态;(收到 FIN 命令,进入 TIME_WAIT 状态,并返回 ACK 命令)
2.保持 2 个 MSL 时间,即,4 分钟;(MSL 为 2 分钟)

##五:系统参数优化:

默认的linux内核参数考虑的是最通用场景,不符合用于支持高并发访问的web服务器的定义,根据业务特点来进行调整,当nginx作为静态web内容服务器、反向代理或者提供压缩服务器的服务器时,内核参数的调整都是不同的,此处针对最通用的、使nginx支持更多并发请求的TCP网络参数做简答配置,
修改/etc/sysctl.conf来更改内核参数
net.ipv4.ip_nonlocal_bind = 1 #永许非本地IP地址socket监听
net.ipv4.ip_forward = 1 #开启IPv4转发
net.ipv4.tcp_timestamps = 0 #是否开启数据包时间戳(负载均衡不要开,会检查接收的报文,多数人打开同一个连接,可能会丢失)
net.ipv4.tcp_tw_reuse = 1 #端口复用(时用户打开网页,没有操作,服务器尝试断开连接)
net.ipv4.tcp_tw_recycle = 1 #快速回收TIME_WAIT状态,用于大量TIME_OUT场景 (时用户打开网页,没有操作,服务器尝试断开连接)


fs.file-max = 190638 
#表示单个进程较大可以打开的句柄数

net.ipv4.tcp_tw_reuse = 1
#参数设置为1,表示永许将TIME_WAIT状态的socket重新用于新的TCP连接,这将对于服务器来说意义重大,因为总有大量TIME_WAIT状态的连接存在

net.ipv4.tcp_keepalive_time=600
#当keepalive启动时,tcp发送keepalive消息的频度;默认时2小时,将其设置为10分钟,可更快的清理无效连接

net.ipv4.tcp_fin_timeout = 30
#当服务器主动关闭链接时,socket保持FIN_WAIT_2状态的较大时间

net.ipv4.tcp_max_tw_buckets = 5000
#表示操作系统永许TIME_WAIT套接字数量的较大值,如超过此值,TIME_WAIT套接字将立刻清除并打印警告信息,默认为8000,过多的TIME_WAIT套接字会使web服务器变慢

net.ipv4.ip_local_port_range = 1024 65000
#定义udp和tcp链接的本地端口的取值范围

net.ipv4.tcp_rmem = 10240 87380 12582912
#定义了TCP接受socket请求缓存的内存最小值、默认值、较大值

net.ipv4.tcp_wmem = 10240 87380 12582912
#定义了TCP发送缓存的最小值、默认值、较大值


net.core.netdev_max_backlog = 8096
#当网卡接收数据包的速度大于内核处理速度时,会有一个队列保存这些数据包,这个参数表示该列队的较大值

net.core.rmem_default = 6291456
#表示内核套接字接收缓存区默认大小

net.core.wmem_default = 6291456
#表示内核套接字发送缓存区默认大小

net.core.rmem_max = 12582912
#表示内核套接字接收缓存区较大大小

net.core.wmem_max = 12582912
#表示内核套接字发送缓存区较大大小
注意:以上的四个参数,需要根据业务逻辑和实际的硬件成本来综合考虑

net.ipv4.tcp_syncookies=1
#与性能无关。用于解决TCP的SYN攻击

net.ipv4.tcp_max_syn_backlog = 8192
#这个参数表示TCP三次握手建立阶段接收SYN请求队列的较大长度,默认1024,将其设置的大一些可使出现nginx繁忙来不及accept新连接时,linux部至于丢失客户端发起的链接请求

net.ipv4.tcp_tw_recycle = 1
#这个参数用于设置启用timewait快速回收

net.core.somaxconn=262114
#选项默认值时128,这个参数用于调节系统同时发起的TCP连接数,在高并发的请求中,默认的值可能会导致链接超市或者重传,因此需要结合高并发请求数来调节此值

net.ipv4.tcp_max_orphanx=262114
#选项用于设定系统中最多有多少个TCP套接字不被关联到任何一个用户文件句柄上。如果超过这个数字,孤立链接将立即被复位并输出警告信息。这个限制只是为了防止简单的DOS共集。不用过分依靠这个限制设置认为的减少这个值,更多的情况时增加这个值

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忙里偷闲学python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值