HAproxy集群搭建和配置

本文详细介绍了如何通过HAProxy实现负载均衡,包括配置四台Web服务器、一台调度器及测试主机,搭建httpd+mysql+php环境,以及配置HAProxy进行不同类型的请求分发,并通过测试验证了配置的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.准备四台web服务器30.40.50.60,  一台20调度器,一台10测试主机

搭建httpd+mysql+php

网站 根目录下创建三个文件

[root@web50 ~]# echo 192.168.4.50 > /var/www/html/index.html

[root@web50 ~]# echo web50 > /var/www/html/test.html

[root@web50 ~]# vim /var/www/html/test.php

<?php
echo "hello web50";
?>

[root@web50 ~]# ls /var/www/html
index.html  test.html  test.php
 

2.配置HAproxy (192.168.4.20)

先在20上安装haproxy

[root@haproxy20 ~]# yum list |grep haproxy
haproxy.x86_64                          1.5.14-3.el7               haha         
[root@haproxy20 ~]# yum -y install haproxy

备份一下haproxy的配置文件到opt下

[root@haproxy20 ~]# cp /etc/haproxy/haproxy.cfg  /opt/

打开配置文件并修改

[root@haproxy20 ~]# vim /etc/haproxy/haproxy.cfg

修改如下(数字代表行号)

 63 frontend  weblb 192.168.4.20:80               #指定分发主机
 64     acl htmlpath       path_end       -i .html     #识别以html结尾的访问请求并分发给htmlgrp组的机器
 65     acl phppath         path_end       -i .php    #识别以php结尾的访问请求并分发给phpgrp组的机器
 66 
 67     use_backend htmlgrp          if htmlpath   #   
 68     use_backend phpgrp           if phppath
 69     default_backend              htmlgrp
 70 
 71 backend htmlgrp
 72     balance     roundrobin                                #roundrobin 表示轮询的方式
 73     server  web30 192.168.4.30:80 check        #给htmlgrp下分配主机,check代表检查端口使用是否正常
 74     server  web40 192.168.4.40:80 check
 75 
 76 backend phpgrp
 77     balance     roundrobin
 78     server  web50 192.168.4.50:80 check       #给phpgrp下分配主机,check代表检查端口使用是否正常
 79     server  web60 192.168.4.60:80 check
保存退出

3. 启动haproxy服务

[root@haproxy20 ~]# systemctl start haproxy

4.测试

[root@pc10 ~]# elinks --dump http://192.168.4.20/test.html
   web30
[root@pc10 ~]# elinks --dump http://192.168.4.20/test.html
   web40
[root@pc10 ~]# elinks --dump http://192.168.4.20/test.html
   web30
[root@pc10 ~]# elinks --dump http://192.168.4.20/test.html
   web40
 

[root@pc10 ~]# elinks --dump http://192.168.4.20/test.php
   hello web50
[root@pc10 ~]# elinks --dump http://192.168.4.20/test.php
   hello web60
[root@pc10 ~]# elinks --dump http://192.168.4.20/test.php
   hello web50
[root@pc10 ~]# elinks --dump http://192.168.4.20/test.php
   hello web60

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值