Keepalived + Nginx 实现高可用 Web 负载均衡发布时间:2018/3/31 11:33:00 阅读次数:

  

一、Keepalived 简要介绍

Keepalived 是一种高性能的服务器高可用或热备解决方案, Keepalived 可以用来防止服务器单点故障的发生,通过配合 Nginx 可以实现 web 前端服务的高可用。

VIP

IP

主机名

Nginx端口

默认主从

192.168.2.10

192.168.2.5

wangdun1

88

MASTER

192.168.2.10

192.168.2.6

Wangdun2

88

BACKUP

二、系统和软件准备

CentOS 6.5 x64
keepalived-1.2.18.tar.gz
nginx-1.13.0.tar.g

三、安装Nginx

1.安装编译 Nginx 所需的依赖包

[root@wangdun1 ~]# yum install gcc gcc-c++ make automake autoconf libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel 

2.下载Nginx

[root@wangdun1 ~]# cd /usr/local/src/

[root@wangdun1 src]# wget http://nginx.org/download/nginx-1.13.0.tar.gz

3.编译安装 Nginx

[root@wangdun1]# tar -zxvf nginx-1.13.0.tar.gz

[root@wangdun1]# cd nginx-1.13.0

[root@wangdun1]#./configure --prefix=/usr/local/nginx

[root@wangdun1]# make && make install

4.配置 Nginx

[root@wangdun1 ~]# vim /usr/local/nginx/conf/nginx.conf

修改 两个节点Nginx 首页内容:

[root@wangdun1 ~]# vim /usr/local/nginx/html/index.html

5.系统防火墙打开端口 88

6.测试 Nginx 是否安装成功

7.启动 Nginx

[root@wangdun1 ~]# /usr/local/nginx/sbin/nginx

重启 Nginx

[root@wangdun1 ~]# /usr/local/nginx/sbin/nginx -s reload

8.设置 Nginx 开机启动

9.分别访问两个 Nginx

四、安装 Keepalived

1.上传keepalived

上传keepalived-1.2.18.tar.gz /usr/local/src 目录

 

2.解压安装

[root@wangdun1 ~]# cd /usr/local/src  

[root@wangdun1 ~]# tar -zxvf keepalived-1.2.18.tar.gz

[root@wangdun1 ~]# cd keepalived-1.2.18 

[root@wangdun1 ~]#./configure --prefix=/usr/local/keepalived

[root@wangdun1 ~]# make && make install

 

3. keepalived 设置为系统服务

因为没有使用 keepalived 的默认路径安装(默认是/usr/local ,安装完成之后,需要做一些工作复制默认配置文件到默认路径

[root@wangdun1 ~]# mkdir /etc/keepalived 

[root@wangdun1 ~]# cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/ 

[root@wangdun1 ~]# cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/ 

[root@wangdun1 ~]# cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/ 

[root@wangdun1 ~]# ln -s /usr/local/sbin/keepalived /usr/sbin/ 

[root@wangdun1 ~]# ln -s /usr/local/keepalived/sbin/keepalived /sbin/ 

 

设置 keepalived 服务开机启动

[root@wangdun1 ~]# chkconfig keepalived on  

4.修改 Keepalived 配置文件

(1) MASTER 节点配置文件(192.168.2.5

(2)BACKUP 节点配置文件(192.168.2.6

5.编写 Nginx 状态检测脚本

编写 Nginx 状态检测脚本 /etc/keepalived/nginx_check.sh脚本要求:如果 nginx 停止运行,尝试启动,如果无法启动则杀死本机的 keepalived 进程, keepalied将虚拟 ip 绑定到 BACKUP 机器上。 内容如下:

保存后,给脚本赋执行权限:

[root@wangdun1 ~]# chmod +x /etc/keepalived/nginx_check.sh 

6.启动 Keepalived

[root@wangdun1 ~]# service keepalived start

7.Keepalived+Nginx 的高可用测试

同时启动192.168.2.5192.168.2.6上的NginxKeepalived,我们通过VIP(192.168.2.10)来访问Nginx,如下

我们关闭192.168.2.5上的KeepalivedNginx

[root@wangdun1 ~]# service keepalived stop

[root@wangdun1 ~]# /usr/local/nginx/sbin/nginx -s stop

此时,再通过VIP(192.168.2.10)来访问Nginx,如下


我们再开启192.168.2.5上的KeepalivedNginx

[root@wangdun1 ~]# service keepalived start

因为我们写了脚本nginx_check.sh,这个脚本会为我们自动启动Nginx

此时,我们再通过VIP(192.168.2.10)来访问Nginx,如下

至此,Keepalived + Nginx 实现高可用 Web 负载均衡搭建完毕。