CentOS6下使用Haproxy搭建Web群集

CentOS6下使用Haproxy搭建Web群集-Linux-me

1.编译安装Nginx服务器

[root@localhost ~]# yum -y install pcre-devel zlib-devel wget vim gcc gcc-c++
[root@localhost ~]# wget http://nginx.org/download/nginx-1.6.0.tar.gz
[root@localhost ~]# useradd -M -s /sbin/nologin  nginx
[root@localhost ~]# tar zxvf nginx-1.6.0.tar.gz 
[root@localhost ~]# cd nginx-1.6.0
[root@localhost nginx-1.6.0]# ./configure --prefix=/usr/local/ngxin --user=nginx --group=nginx
[root@localhost nginx-1.6.0]# make && make install
[root@localhost nginx-1.6.0]# cd /usr/local/ngxin/html/
[root@localhost html]# echo "Server 192.168.1.21" > test.html
[root@localhost html]# /usr/local/ngxin/sbin/nginx
[root@localhost html]# netstat -anpt | grep nginx
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      1690/nginx

两台Nginx服务器配置都一样,唯一不一样的就是test.html网页;安装完成后测试访问两台Nginx服务器,如下图

CentOS6下使用Haproxy搭建Web群集-Linux-me

2.编译安装Haproxy

[root@localhost ~]# yum -y install pcre-devel bzip2-devel
[root@localhost ~]# tar zxvf haproxy-1.4.24.tar.gz
[root@localhost ~]# cd haproxy-1.4.24
[root@localhost haproxy-1.4.24]# make TARGET=linux26
[root@localhost haproxy-1.4.24]# make install
[root@localhost haproxy-1.4.24]# mkdir /etc/haproxy/
[root@localhost haproxy-1.4.24]# cp examples/haproxy.cfg /etc/haproxy/
修改/etc/haproxy.cfg文件
# this config needs haproxy-1.1.28 or haproxy-1.2.1
global
        log 127.0.0.1   local0
        log 127.0.0.1   local1 notice
        #log loghost    local0 info
        maxconn 4096
        chroot /usr/share/haproxy
        uid 99
        gid 99
        daemon
        #debug
        #quiet
defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        maxconn 2000
        contimeout      5000
        clitimeout      50000
        srvtimeout      50000
listen  webcluster 0.0.0.0:80
        option  httpchk GET /index.html
        balance roundrobin
        server  inst1 192.168.1.21:80 check inter 2000 fall 3
        server  inst2 192.168.1.22:80 check inter 2000 fall 3

创建自启动脚本

[root@localhost ~]# cp ~/haproxy-1.4.24/examples/haproxy.init /etc/init.d/haproxy
[root@localhost ~]# ln -s /usr/local/sbin/haproxy /usr/sbin/haproxy
[root@localhost ~]# service iptables stop
[root@localhost ~]# /etc/init.d/haproxy start
Starting haproxy:                                          [确定]
[root@localhost ~]# netstat -apn | grep 80
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      1539/haproxy
如果你的haproxy启动时提示:Starting haproxy: [ALERT] 364/214849 (1296) : [/usr/sbin/haproxy.main()] Cannot chroot(/usr/share/haproxy).
说明你没有创建文件夹.执行:mkdir /usr/share/haproxy即可

通过前面的步骤就可以完成搭建Haproxy的Web集群;

首先测试高性能(如下如图)

CentOS6下使用Haproxy搭建Web群集-Linux-me

再测试高可用(测试高可用的时候先关闭一台nginx服务器,我这边将Nginx1服务器的服务关闭)

CentOS6下使用Haproxy搭建Web群集-Linux-me

再将Nginx1服务启用测试

CentOS6下使用Haproxy搭建Web群集-Linux-me

本次实验到此结束,有问题的可以在下方评论或者留言板留言。