环境介绍
使用haproxy作为两台apache服务器的反向代理
系统:CentOS7
haproxy版本:1.4.24
服务器 | IP地址 |
---|---|
haproxy | 192.168.218.4 |
apache1 | 192.168.218.5 |
apache2 | 192.168.218.6 |
部署apache站点
使用yum方式安装apache
yum -y install httpd
安装httpd后会自动生成/var/www/html目录
在该目录下存放站点网页,并启动httpd服务
配置站点1
echo "this is apache1" > /var/www/html/index.html
systemctl restart httpd
配置站点2
echo "this is apache2" > /var/www/html/index.html
systemctl restart httpd
源码编译安装haproxy
安装haproxy依赖环境
yum install -y \
pcre-devel \
bzip2-devel \
gcc \
gcc-c++ \
make
解压源码包
tar xf haproxy-1.4.24.tar.gz
可使用-C参数指定解压路径
进入源码目录,进行编译安装
make TARGET=linux26
make install
创建/etc/haproxy,用于存放配置文件
mkdir /etc/haproxy
# 将源码包目录下examples/haproxy.cfg复制到/etc/haproxy/
cp examples/haproxy.cfg /etc/haproxy/
修改配置文件/etc/haproxy/haproxy.cfg,如下图
将haproxy添加到service服务
# 将源码目录下的examples/haproxy.init复制到/etc/init.d/下
cp /root/haproxy-1.4.24/examples/haproxy.init /etc/init.d/haproxy
# 添加执行权限
chmod +x /etc/init.d/haproxy
# 添加service服务
chkconfig --add /etc/init.d/haproxy
ln -s /usr/local/sbin/haproxy /usr/sbin/
开启服务
service haproxy start
Starting haproxy (via systemctl): [ OK ]
# 查看服务状态
netstat -antp|grep haproxy
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 2120/haproxy
在浏览器中访问haproxy,我们可以看到haproxy代理了apache的站点
haproxy日志配置
修改配置文件
重启haproxy服务
service haproxy restart
创建日志配置
vim /etc/rsyslog.d/haproxy.conf
if ($programname == 'haproxy' and $syslogseverity-text == 'info')
then -/var/log/haproxy/haproxy-info.log
&~
if ($programname == 'haproxy' and $syslogseverity-text == 'notice')
then -/var/log/haproxy/haproxy-notice. log
&~
重启rsyslog.service
systemctl restart rsyslog.service
浏览器多刷新几次后,增加了访问日志,再查看日志文件/var/log/haproxy/haproxy-info.log
就能看到测试的访问请求