写在前面:如果此文有幸被某位朋友看见并发现有错的地方,希望批评指正。如有不明白的地方,愿可一起探讨。



案例拓扑图


haproxy实现资源动静分离的简单案例

说明:haproxy服务器安装了两张网卡,eth0以桥接的方式连接,eth1连接到VMnet3上;web1和web2也都连接到VMnet3上。

配置上游服务器web1


默认情况下,httpd服务已经安装,因此只需为其添加测试页面并启动服务即可

# vim /var/www/html/index.html
    <h1>Hello,192.168.3.101</h1>
# /etc/init.d/httpd start

配置上游服务器web2


安装php服务

# yum -y install php

添加测试页面并启动服务

# vim /var/www/html/index.php
    <h1>Hello,192.168.3.102</h1>
    <?php
        phpinfo();
    ?>
# /etc/init.d/httpd start

配置haproxy服务器


安装haproxy服务

# yum -y install haproxy

备份haproxy.cfg文件

# cd /etc/haproxy/
# cp haproxy.cfg haproxy.cfg.bak

删除haproxy.cfg文件中以# main frontend which proxys to the backends以后的所有内容

编辑/etc/haproxy/haproxy.cfg配置文件,在haproxy.cfg添加如下内容

frontend main
    bind :80
    maxconn 6000
    acl url_static path_beg -i /p_w_picpaths /stylesheets /vedios /javascript
    acl url_static path_end -i .jpg .html .css .js .png .gif
    use_backend statics if url_static
    default_backend    dynamics
backend statics
    balance roundrobin
    server s1 192.168.3.101 check port 80 maxconn 3000
    server b1 127.0.0.1:8080 backup check port 8080
backend dynamics
    balance roundrobin
    server d1 192.168.3.102 check port 80 maxconn 3000
    server b2 127.0.0.1:8080 backup check port 8080
listen stats
    bind :8888
    stats enable
    stats hide-version
    stats uri /hap?stats
    stats auth muluhe:muluhe
    stats admin if TRUE

给haproxy提供测试页面

# vim /var/www/html/index.html
    <h1>I'm so sorry, Site is maintainning</h1>

修改httpd.conf配置文件,将Listen 80改为Listen 8080

启动haproxy服务器上的httpd服务和haproxy服务

# /etc/init.d/httpd start
# /etc/init.d/haproxy start

查看haproxy服务器状态图形管理界面

haproxy实现资源动静分离的简单案例

测试haproxy动静分离功能


在浏览器中键入10.170.2.80/index.html,可得到如下页面

haproxy实现资源动静分离的简单案例

在浏览器中键入10.170.2.80/index.php,可得到如下页面

haproxy实现资源动静分离的简单案例