Linux:Haproxy 动静分离实验
实验拓扑图如下:
客户端: 192.168.186.165
静态主机:192.168.186.163
动态主机:192.168.186.164
代理主机:192.168.186.162
===============================
静态主机
静态主机使用httpd
yum -y install httpd
echo "I am 80 ." >/var/www/html/index.html
配置虚拟主机:
cp /usr/share/doc/httpd-2.4.6/httpd-vhosts.conf /etc/httpd/conf.d/
vim /etc/httpd/conf.d/httpd-vhosts.conf
配置如下:
Listen 81
Listen 82
<VirtualHost *:81>
DocumentRoot "/var/www/html/81/"
ErrorLog "/var/log/httpd/81.com-error_log"
CustomLog "/var/log/httpd/81.com-access_log" common
</VirtualHost>
<VirtualHost *:82>
DocumentRoot "/var/www/html/82/"
ErrorLog "/var/log/httpd/82.com-error_log"
CustomLog "/var/log/httpd/82.com-access_log" common
</VirtualHost>
mkdir /var/www/html/{81,82}
echo "I am 81." > /var/www/html/81/index.html
echo "I am 82." > /var/www/html/82/index.html
systemctl restart httpd
动态主机:
安装httpd php
yum -y install httpd php
修改 vim /etc/httpd/conf/httpd.conf
.....
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
......
编写测试页面:
vim /var/www/html/index.php
<?php
echo "PHP is OK.";
?>
代理主机:
vim /etc/haproxy/haproxy.cfg
.......
frontend main *:5000
# acl url_static path_beg -i /static /images /javascript /stylesheets
# acl url_static path_end -i .jpg .gif .png .css .js
acl url_php path_end -i .php
use_backend php if url_php
default_backend static
#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
backend php
balance roundrobin
server php 192.168.186.164:80 check
#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend static
balance roundrobin
server web1 192.168.186.163:80 check
server web2 192.168.186.163:81 check
server web3 192.168.186.163:82 check
systemctl restart haproxy
客户端
curl 192.168.186.162:5000 (多访问几次,显示不然主机的结果则成功)
curl 192.168.186.162:5000/index.php (显示php的内容则成功)
=====================================
如果想在web端获取访问的真实IP,只需要在httpd配置文件中的日志格式加入 %{X-Forwarded-For}i
=======================================
如果想同时对mysql进行调度,可以在proxy的配置文件最后加上:
listen mysql
bind *:3306
mode tcp
balance roundrobin
server mysql1 192.168.186.163:3306 weight 1 check inter 1s rise 2 fall 2
server mysql2 192.168.186.164:3306 weight 1 check inter 1s rise 2 fall 2
还要在数据库给代理授权(这里就不详细说了)