keepalived+haproxy(双主)+nginx(静态)+lamp(动态)部署phpBB

本文介绍如何使用HAProxy和Keepalived搭建高性能、高可用的反向代理集群,支持HTTPS协议,并结合Nginx和LAMP实现动静分离。

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

简介

    haproxy为高性能的反向代理服务器,在向后端server调度方面支持很多的调度算法:roundrobin,source,uri,url_param,hdr(),leastconn等,且支持动态权重调整的一致性hash,在后端为cache server时很好的提高cache命中率;所以相比nginx反向代理,haproxy调度功能更为强大,另外haproxy提供自带的gui接口,方便直接在web页面管理前、后端服务器,只需要在配置文件中开启即可。

    nginx自身在处理web静态页面方面非常强大,其采用模块化设计,有较好的扩展性,但不支持模块动态装卸载(Tengine支持模块动态装卸载),nginx具有高可靠性,支持热部署,低内存消耗等优点,其在设计之初就吸纳了最新的技术,如支持事件驱动、异步IO等,并发处理能力强大。

    apache结合php处理动态页面功能强大,php可直接以模块的形式加载到httpd,而nginx需要通过fastcgi协议与后端php通信。所以结合各组件优点,我们这里采用haproxy(支持https)+nginx(静态)+lamp(动态)架构,最后通过keepalived实现对haproxy高可用。此外本实验中对phpBB全站点使用https协议。


下图为本次实验架构图:

                           

                                                                                                                        图1

                                                                                                                    图2

架构图说明

这里有2幅架构图,图1中,后端各主机均在同一网段,这也是我们这次实验所采用的架构;图2中后端static server group和dynamic server group不在同一网段,二者之间需要路由器相连,Router的地址:eth0 --> 192.168.100.80 eth1 --> 192.168.200.80非但如此,采用图2架构还需在haproxy和各后端server上添加静态路由:

haproxy1:  route add -net 192.168.200.0/24 gw 192.168.100.80 dev eth1

haproxy2:  route add -net 192.168.100.0/24 gw 192.168.200.80 dev eth1

Nginx1:      routeadd -net 192.168.200.0/24 gw 192.168.100.80 dev eth0

Nginx2:      routeadd -net 192.168.200.0/24 gw 192.168.100.80 dev eth0

LAMP1:      routeadd -net 192.168.100.0/24 gw 192.168.200.80 dev eth0

LAMP2:      routeadd -net 192.168.100.0/24 gw 192.168.200.80 dev eth0

为简便,这里我们采用架构图1。这里我们用virtualbox准备6台linux主机,各主机IP地址、Gateway及所需安装软件等如下表所配置,这里我们将192.168.0.0/24网络模拟为公网,192.168.100.0/24为服务器内网网段。前端为2台haproxy组成的反向代理服务器,并实现双主高可用:所谓双主,即haproxy1和haproxy2都正常工作,均同时为后端server提供反向代理和调度功能,用户可通过DNS解析后的192.168.0.50和192.168.0.51两个地址访问我们的网站。客户端请求的所有phpBB静态页面由前端的haproxy调度至后端的2台nginx组成的服务器组响应;用户请求的所有phpBB动态页面由前端的haproxy调度至后端的2台lamp组成的服务器组响应。

6台linux主机上所需资源如下:


 

软件安装

按照上面的清单,分别在各主机上部署所需软件,对于清单中HAProxy需要安装ntpd服务器的原因在于keepalived的运行需要后端server与前端服务器时钟保持同步,否则对后端server的健康状态检测会出现异常。

①、haproxy

haproxy在centos6.8上可以直接使用yum方式:

[root@centos68 ~]# yum install -y haproxy

目前系统提供的默认版本是1.5.18,且支持openssl:

[root@centos68 ~]# rpm -q haproxy ; ldd $(which haproxy)| grep ssl

haproxy-1.5.18-1.el6.x86_64

libssl.so.10 => /usr/lib64/libssl.so.10(0x00007f05e085c000)

如果是手动编译安装,则需要先在官网下载程序包,并添加对openssl的支持,下面是手动编译步骤:

[root@centos68 ~]# yum install -y openssl openssl-devel readline-devel pcre-devel libssl-dev libpcre3
[root@centos68 ~]# wget http://www.haproxy.org/download/1.6/src/haproxy-1.6.13.tar.gz
[root@centos68 ~]# tar xf haproxy-1.6.13.tar.gz ; cd haproxy-1.6.13
[root@centos68 haproxy-1.6.13]# make TARGET=linux2628 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_CRYPT_H=1 USE_LIBCRYPT=1
[root@centos68 haproxy-1.6.13]# ldd $(which haproxy) | grep ssl
libssl.so.10 => /usr/lib64/libssl.so.10 (0x00007f05e085c000) 
[root@centos68 haproxy-1.6.13]# make install PREFIX=/usr/local/haproxy
[root@centos68 haproxy-1.6.13]# vi /etc/profile.d/haproxy.sh
#!/bin/bash
export PATH=$PATH:/usr/local/haproxy/sbin/
[root@centos68 haproxy-1.6.13]# source /etc/profile.d/haproxy.sh

创建配置文件目录及拷贝并修改启动脚本:

[root@centos68 haproxy-1.6.13]# mkdir -p /etc/haproxy
[root@centos68 haproxy-1.6.13]# cp examples/haproxy.init /etc/rc.d/init.d/haproxy
[root@centos68 haproxy-1.6.13]# vi /etc/rc.d/init.d/haproxy
BIN=/usr/local/haproxy/sbin/$BASENAME
CFG=/etc/$BASENAME/$BASENAME.cfg
PIDFILE=/var/run/$BASENAME.pid
LOCKFILE=/var/lock/subsys/$BASENAME

至此haproxy已经安装完毕,最后我们根据架构图提供haproxy的配置文件:

 

[root@centos68 ~]# vi /etc/haproxy/haproxy.cfg
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    log         127.0.0.1 local2
    chroot      /var/lib/haproxy
    pidfile     /var/run/haproxy.pid
    maxconn     40000
    user        haproxy
    group       haproxy
    daemon
    tune.ssl.default-dh-param 2048
    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option 		    	        http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend  http_frontend
    bind   *:80
    bind *:443 ssl crt /etc/haproxy/haproxy.pem  # 网站证书文件
    mode http
    log global
    option httpclose
    option logasap
    option dontlognull
    option forwardfor except 127.0.0.1 header X-Client if-none
    capture request header Host len 20
    capture request header Referer len 60
    reqadd X-Forwarded-Proto:\ https
    #rspadd Via:\ haproxy.example.com
    acl url_static path_beg -i /static /images /javascript /stylesheets
    acl url_static path_end -i .jpg .jpeg .png .bmp .gif .css .js
    redirect scheme https if !{ ssl_fc }       # 全站采用https协议
    use_backend static_servers if url_static
    default_backend dynamic_servers
    
    
#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
backend static_servers
    mode http
    balance    roundrobin
    #option     httpchk  HEAD  /healthchk.html
    server     static1 192.168.100.64:80 check inter 1000 rise 2 fall 4 weight 1 maxconn 6000
    server     static2 192.168.100.65:80 check inter 1000 rise 2 fall 4 weight 1 maxconn 6000
    http-request set-header X-Forwarded-Port %[dst_port]
    http-request add-header X-Forwarded-Proto https if { ssl_fc }
backend dynamic_servers
    mode http
    balance    roundrobin
    #cookie     dynamic_cookie insert nocache indirect
    server     https_dynamic1 192.168.200.70:80 check inter 2000 rise 2 fall 4 weight 1 maxconn 1000 
    server     https_dynamic2 192.168.200.71:80 check inter 2000 rise 2 fall 4 weight 1 maxconn 1000 
    http-request set-header X-Forwarded-Port %[dst_port]
    http-request add-header X-Forwarded-Proto https if { ssl_fc }

listen stats
    bind *:9090
    stats enable
    stats uri /haproxy?stats
    stats hide-version
    stats auth admin:yourpassword
    stats admin if TRUE

②、haproxy.cfg配置说明

haproxy的配置文件位于:/etc/haproxy/haproxy.cfg,该配置文件中的一个重点是添加对https协议的支持,为了实现该目的,需要做如下操作:

我们知道,haproxy代理ssl有三种方式:第一种,haproxy 自身提供ssl 证书,仅是客户端与haproxy之间传输https协议,而haproxy与后端的web server仍然传输http;第二种为SSL透传,haproxy 本身工作于tcp传输层,https由后端server直接处理,但haproxy不对https报文做任何修改,这就意味着后端server失去了对客户端IP、端口及使用协议的记录;第三种,SSL连接在负载均衡器处终止,按需求调整,然后作为新的SSL连接代理到后端服务器。这可能会提供最大的安全性和发送客户端信息的能力。这样做的代价是更多的CPU能耗和稍复杂的配置。实验中我们采用第一种,所以我们需要提供haproxy的ssl证书文件:

因为是实验,所以我们需要生成自签署证书cacert.pem、应用程序haproxy证书haproxy.crt,应用程序haproxy私钥haproxy.key等文件,具体私钥及证书生成步骤这里不再详述。最后将haproxy.crt和haproxy.key合并为一个文件:

[root@centos68 ~]# cd /etc/haproxy

[root@centos68 haproxy]# cat haproxy.crt haproxy.key | tee haproxy.pem

而上面生成的haproxy.pem正是haproxy.cfg所需要的:

bind *:443 ssl crt /etc/haproxy/haproxy.pem

③、keepalived安装与配置

我们需要在前端部署有haproxy的两台server上安装keepalived,其安装过程较为简单,直接使用yum安装即可:

[root@centos68 ~]# yum install -y keepalived

[root@centos68 ~]# rpm -q keepalived

keepalived-1.2.13-5.el6_6.x86_64

haproxy1上的keepalived配置:

 

! Configuration File for keepalived

global_defs {
   notification_email {
     root@localhost
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id www.example.com

}

vrrp_script chk_haproxy {
   script "killall -0 haproxy &> /dev/null"
   interval 1
   weight -20
}
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 256f6df6
    }
    virtual_ipaddress {
       192.168.0.50/24 dev eth0 label eth0:0
    }
    track_script {  
        chk_haproxy
    } 
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault "/etc/keepalived/notify.sh fault"
}

vrrp_instance VI_2 {
    state BACKUP
    interface eth0
    virtual_router_id 52
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 19afa2c5
    }
    virtual_ipaddress {
       192.168.0.51/24 dev eth0 label eth0:1
    }
    track_script {  
        chk_haproxy
    } 
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault "/etc/keepalived/notify.sh fault"
}

haproxy2上的keepalived配置:

 

! Configuration File for keepalived

global_defs {
   notification_email {
     root@localhost
   }
   notification_email_from Alexandre.Cassen@firewall.loc
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id centos66.example.com
}
vrrp_script chk_haproxy {
   script "killall -0 haproxy &> /dev/null"
   interval 1
   weight -20
   }

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 256f6df6
    }
    virtual_ipaddress {
        192.168.0.50/24 dev eth0 label eth0:0
    }
    track_script {  
        chk_haproxy
    } 
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault "/etc/keepalived/notify.sh fault"
}
vrrp_instance VI_2 {
    state MASTER
    interface eth0
    virtual_router_id 52
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 19afa2c5
    }
    virtual_ipaddress {
        192.168.0.51/24 dev eth0 label eth0:1
    }
    track_script {  
        chk_haproxy
    } 
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault "/etc/keepalived/notify.sh fault"
}

消息通知脚本notify.sh:

#!/bin/bash
#Date:2017-10-07
vip=192.168.0.50
contact="root@localhost"

notify() {
   mailsubject="`hostname` to be $1: $vip floating"
   mailbody="`date +'%F %H:%M:%S'`: vrrp transition, `hostname` changed to be $1"
   echo "$mailbody" | mail -s "$mailsubject" $contact
}
case "$1" in 
master)
    notify master
    exit 0
    ;;
backup)
    notify backup
    exit 0
    ;;
fault)
    notify fault
    exit 0
    ;;
*)
    echo "Usage: `basename $0` {master|backup|fault}"
    exit 1 
    ;;
esac

④、ntpd的安装与配置

由于前端keepalived与后端各server通信需要保证时钟同步,所以我们需要在前端的其中一台主机上安装ntpd服务器,注意本次实验采用的是架构图1,如果是架构图2,那么前端的2台haproxy服务器上均要部署ntpd。

[root@centos66 ~]# yum install -y ntpd
[root@centos66 ~]# vi /etc/ntpd.conf
# For more information about this file, see the man pages
# ntp.conf(5), ntp_acc(5), ntp_auth(5), ntp_clock(5), ntp_misc(5), ntp_mon(5).

driftfile /var/lib/ntp/drift

# Permit time synchronization with our time source, but do not
# permit the source to query or modify the service on this system.
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery

restrict ntp1.aliyun.com
restrict ntp2.aliyun.com
restrict ntp3.aliyun.com
restrict ntp4.aliyun.com
restrict ntp5.aliyun.com
# Permit all access over the loopback interface.  This could
# be tightened as well, but to do so would effect some of
# the administrative functions.
restrict 127.0.0.1 
restrict -6 ::1
restrict 192.168.100.0 mask 255.255.255.0 nomodify
server ntp1.aliyun.com prefer
server ntp2.aliyun.com
server ntp3.aliyun.com
includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys


安装完成后启动即可:service ntpd start ;chkconfig ntpd on

后端各server添加crontab任务计划:

[root@www ~]# crontab -e

MAILTO=""

*/10 * * * * /usr/sbin/ntpdate 192.168.100.16 &> /dev/null

这样设置完成后,后端的各server每10分钟就会与前端的ntpd进行一次时钟同步。

⑤、Static Server Group

静态服务器组的组成是由各linux主机上部署nginx来完成,在centos6.8上也可以直接使用yum来安装:

[root@centos66 ~]# yum install -y nginx

然后对后端各主机上的nginx配置文件进行配置:

[root@centos66 ~]# vi /etc/nginx/nginx.conf
# nginx.conf
user  nginx;
worker_processes  1;
worker_rlimit_nofile 51200;
pid /var/run/nginx.pid;
events {
    worker_connections  51200;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    error_log /var/log/nginx/error.log  notice;

    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;

        location / {
            root   /var/www/html/phpBB;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

      }

  } 

⑥、Dynamic Server Group

在后端各server上需要部署httpd+mariadb+php,在centos7上安装过程比较简单,直接使用yum安装即可,这里不再具体给出各软件安装步骤,我们需要在/etc/httpd/conf.d中添加虚拟主机:

[root@www ~]# cd /etc/httpd/conf.d/
[root@www conf.d]# vi vhosts.conf
<VirtualHost *:80>
   DocumentRoot "/var/www/html"
   ServerName  ftp.example.com
</VirtualHost>

<Directory "/var/www/html/phpBB">
   Options Includes ExecCGI FollowSymLinks
   AllowOverride None
   Require all granted
</Directory>

<VirtualHost *:80>
   DocumentRoot "/var/www/html/phpBB"
   ServerName  www.example.com:80
</VirtualHost>

另外需要将配置文件:/etc/httpd/conf/httpd.conf中的"DocumentRoot"这一行注释掉并修改日志格式:

#DocumentRoot "/var/www/html"
LogFormat "%{X-Client}i %{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
#SetEnvIf Request_URI "^/test.html(/.*)?$" dontlog
#CustomLog "logs/access_log" combined env=!dontlog

⑦、部署phpBB

从phpBB官网下载安装包,将安装包分别拷贝至后端各server:Nginx1,Ngine2,LAMP1,LAMP2上的/var/www/html目录下,解压缩并修改所属用户和组,这里以后端的LAMP1来演示,其它各server上的操作步骤与下面类似:

[root@www ~]# cp phpBB-3.2.0.tar.bz2 /var/www/html
[root@www ~]# cd /var/www/html
[root@www html]# tar xf phpBB-3.2.0.tar.bz2
[root@www html]# ls
phpBB3 
[root@www html]# chown -R apache:apache phpBB3
[root@www html]# ln -s phpBB3 phpBB
[root@www html]# chown -R apache:apache phpBB

最后我们在LAMP1和LAMP2上创建数据库

MariaDb[(none)] > create database phpBB;
MariaDb[(none)] > grant all privileges on phpBB.* to phpBB@ '127.0.0.1' identified by 'yourpassword';
MariaDb[(none)] > flush privileges;

上面创建了phpBB数据库名为:phpBB,数据库用户名:phpBB,密码:yourpassword,这在后续的phpBB页面安装过程中需要。

至此各server配置已经完成,最后就需要我们在浏览器安装phpBB了,在浏览器中输入www.example.com进入安装。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值