实战HAProxy (轮循)

环境准备

hostnameIP-wanIP-lan应用
lb0110.0.0.5172.16.1.5HAProxy
web0110.0.0.7172.16.1.7nginx
web0210.0.0.8172.16.1.8nginx
db0110.0.0.51172.16.1.51nginx
lb 作为负载均衡    web01 web02 作为主web服务器   db01 作为备胎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-20241015190553779.png

image-20241015190643293.png

网页统计测试

访问10.0.0.5:9090/haproxy    

用户名 :admin
密码 : admin

image-20241015190703160.png

存活检测测试

web01  web02 停止nginx 
systemctl stop  nginx 

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

image-20241015190751224.png

image-20241015190736493.png

web01 web02 启动nginx
systemctl start  nginx 

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

image-20241015190724722.png

image-20241015190553779.png

天行健,君子以自强不息