使用 HAProxy + Nginx 搭建 Web 群集

HAProxy 是目前比较流行的一种群集调度工具,同类群集调度工具中,同 LVS 对比,LVS 性能最好,但是搭建相对比较复杂,Nginx 的 upstream 模块支持群集功能,但是对群集节点的健康检查功能不强,性能没有 HAProxy 好。

系统环境

主机 IP地址 主要软件
HAProxy 服务器 192.168.100.200 haproxy-1.5.19.tar.gz
Nginx 服务器1 192.168.100.201 nginx-1.12.0.tar.gz
Nginx 服务器2 192.168.100.202 nginx-1.12.0.tar.gz

开始部署

部署 Nginx 服务器

  • 一、 编译安装 Nginx 服务器

    yum install -y pcre-devel zlib-devel gcc gcc-c++ make 
    useradd -M -s /sbin/nologin nginx
    tar zxvf nginx-1.12.0.tar.gz -C /opt
    cd /opt/nginx-1.12.0/
    ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx
    make && make install
  • 安装后的默认信息如下。
    -默认安装目录: /usr/local/nginx
    -默认日志: /usr/local/nginx/logs/
    -默认监听端口:80
    -默认 Web 目录: /usr/local/nginx/html

  • 接下来设置测试页面并启动 Nginx 服务
    echo "<h1>Server 192.168.100.201</h1>" > /usr/local/nginx/html/test.html
    /usr/local/nginx/sbin/nginx    ##启动nginx
    systemctl stop firewalld.service
    setenforce 0
  • 为了方便,网站直接使用 IP 地址访问。在客户端访问 http://192.168.100.201/test.html 进行测试。

  • 搭建 Nginx 服务器2的过程和 Nginx 服务器1的编译安装步骤相同,不同地方在于建立测试页面。
    echo "<h1>Server 192.168.100.202</h1>" > /usr/local/nginx/html/test.html

部署 HAProxy 服务器

  • 编译安装 HAProxy

    yum install pcre-devel bzip2-devel gcc gcc-c++ make -y
    tar zxvf haproxy-1.5.19.tar.gz -C /opt
    cd haproxy-1.5.19/
    make TARGET=linnux26    ##64位系统
    make install
  • HAProxy 服务器配置

    mkdir /etc/haproxy
    cp examples/haproxy.cfg /etc/haproxy/    ##复制haproxy.cfg 文件复制到配置文件目录
  • 编辑配置文件
    vim /etc/haproxy/haproxy.cfg
    chroot /usr/share/haproxy  ##删除两条语句及所有 listen 项目
    redispatch
    ##添加
    listen  webcluster 0.0.0.0:80
        option httpchk GET /test.html
        balance roundrobin
        server inst1 192.168.100.201:80 check inter 2000 fall 3
        server inst2 192.168.100.202:80 check inter 2000 fall 3
  • 复制自启动脚本,并启动服务

    cp /opt/haproxy-1.5.19/examples/haproxy.init /etc/init.d/haproxy
    chmod +x haproxy
    chkconfig --add /etc/init.d/haproxy
    ln -s /usr/local/sbin/haproxy /usr/sbin/haproxy
    service haproxy start
  • Windows 客户端测试(可以看到访问 HAProxy 服务器地址时,轮询访问两台 Nginx 服务器)
    使用 HAProxy + Nginx 搭建 Web 群集
    使用 HAProxy + Nginx 搭建 Web 群集

HAProxy 日志定义分离

  • HAProxy 日志默认输出到系统 syslog 中,查看非常不方便。为了更好的管理日志,可以将 HAProxy 的 info 访问日志和 notice 错误日志记录到不同的日志文件中。

  • 修改配置文件

    vim /etc/haproxy/haproxy.cfg
    ##修改为下面的行
    global
        log /dev/log    local0 info
        log /dev/log    local0 notice
  • 修改 rsyslog 配置,并重启 rsylog 服务

    touch /etc/rsyslog.d/haproxy.conf
    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
    &~
  • 通过客户端访问 HAProxy 服务器,并查看日志
    cd /var/log/haproxy/
    cat haproxy-info.log

猜你喜欢

转载自blog.51cto.com/13625676/2150072