实战HAProxy (轮循)


环境准备

hostname IP-wan IP-lan 应用
lb01 10.0.0.5 172.16.1.5 HAProxy
web01 10.0.0.7 172.16.1.7 nginx
web02 10.0.0.8 172.16.1.8 nginx
db01 10.0.0.51 172.16.1.51 nginx
lb 作为负载均衡    web01 web02 作为主web服务器   web03 作为备胎web服务器

环境搭建

### ld  
1 安装 
yum install haproxy -y

2 编辑配置文件
vim /etc/haproxy/haproxy.cfg

global  
    log         127.0.0.1 local3 
    pidfile     /var/run/haproxy.pid  
    maxconn     4000  
    user        haproxy  
    group       haproxy  
    daemon  
    nbproc     2   
  
defaults  
    mode                    http  
    log                     global  
    option                  httplog  
    option                  dontlognull  
    option                  redispatch  
    retries                 3  
    timeout connect         10s  
    timeout client          1m  
    timeout server          1m  
    maxconn                 3000  
  
listen stats  
    bind *:9090
    mode http
    stats enable
    stats uri /haproxy
    stats auth admin:admin
    stats realm "数据统计页面" 

frontend  web *:80  
    acl url_beg   path_beg -i /static /images /javascript /stylesheets  
    acl url_end   path_end -i .jpg .gif .png .css .js  
    use_backend static if url_beg  
    use_backend media if url_end  
    default_backend app  
  
backend static  
    option forwardfor header X-REAL-IP  
    balance     roundrobin  
    server  static-A 10.0.0.7:80 weight 1 check inter 2000 rise 2 fall 5  
    server  static-B 10.0.0.8:80 weight 1 check inter 2000 rise 2 fall 5  
  
backend media  
    option forwardfor header X-REAL-IP  
    balance     roundrobin  
    server  media-A 10.0.0.7:80 weight 1 check inter 2000 rise 2 fall 5  
    server  media-B 10.0.0.8:80 weight 1 check inter 2000 rise 2 fall 5  
  
backend app  
    option forwardfor header X-REAL-IP  
    balance     roundrobin  
    server  app-A 172.16.1.7:80 weight 1 check inter 2000 rise 2 fall 5  
    server  app-B 172.16.1.8:80 weight 1 check inter 2000 rise 2 fall 5  
    server  app-C 172.16.1.51:80 weight 1 check inter 2000 rise 2 fall 5 backup
    
    
3 .启动
systemctl start haproxy
systemctl enable haproxy
#### web服务器

yum install nginx -y

echo $hostname > /usr/share/nginx/html/index.html


测试

负载测试

访问 10.0.0.5 多刷新 只有web01 web02

image-20240921145742014

image-20240921145822028

网页统计测试

访问10.0.0.5:9090/haproxy    

用户名 :admin
密码 : admin

image-20240921150020826

image-20240921150556696

存活检测测试

web01  web02 停止nginx 
systemctl stop  nginx 

访问 web页面     http://10.0.0.5
访问 后端数据页面 http://10.0.0.5:9090/haproxy

image-20240921150742248image-20240921150809594

web01 web02 启动nginx
systemctl start  nginx 

访问 web页面     http://10.0.0.5
访问 后端数据页面 http://10.0.0.5:9090/haproxy

image-20240921151017761

image-20240921151023612