高可用负载均衡集群

一、Nginx 配置优化

1.1 连接数优化

当 Nginx 作为负载均衡服务器时,能够接收的并发连接应该越多越好。为了测试服务器的并发能力,可以利用 jmeter 或者 Apache Bench 工具,这里使用 Apache Bench 进行测试。

首先安装 Apache2:

apt install apache2

安装完成后,通过如下命令验证安装成功:

root@wuychn:/etc/apache2# apache2 -version
Server version: Apache/2.4.29 (Ubuntu)
Server built:   2019-04-03T13:22:37

默认Apache2监听80端口,此处修改为8081。编辑/etc/apache2/ports.conf,修改为8081即可。之后重启 Apache2:

/etc/init.d/apache2 restart

之后,就可以使用ApacheBench 了,该工具的使用方式如下:

ab -n500 -c500 http://192.168.11.200/

-n 表示发送的请求总数,-c 表示并发数,后面的网址是请求的服务器 URL 地址。 ApacheBench 目前只能使用 HTTP 1.0 协议进行请求。

执行上述命令,结果如下:

root@wuychn:/# ab -n500 -c500 http://192.168.11.200/
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.11.200 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Finished 500 requests                                            #完成500个请求


Server Software:        nginx/1.14.2                             #服务器软件
Server Hostname:        192.168.11.200                           #服务器主机名
Server Port:            80                                       #服务器端口号

Document Path:          /                                        #文档路径
Document Length:        612 bytes                                #文档大小

Concurrency Level:      500                                      #并发数
Time taken for tests:   0.042 seconds                            #完成测试所用的时间
Complete requests:      500                                      #完成的请求数
Failed requests:        0                                        #失败的请求数
Total transferred:      422500 bytes                             #总传输量大小
HTML transferred:       306000 bytes                             #HTML数据量大小
Requests per second:    12032.25 [#/sec] (mean)                  #平均每秒请求数
Time per request:       41.555 [ms] (mean)                       #平均每次并发请求所用时间
Time per request:       0.083 [ms] (mean, across all concurrent requests) #平均每个请求所用时间
Transfer rate:          9928.95 [Kbytes/sec] received            #平均每秒传输的数据量

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       14   16   1.1     15      18
Processing:    10   13   1.7     14      15
Waiting:        7   10   2.2     10      14
Total:         26   28   1.2     28      31

Percentage of the requests served within a certain time (ms)     #各请求的时间分布如下     
  50%     28                                                     #50%的请求花了28毫秒
  66%     29
  75%     29
  80%     29
  90%     30
  95%     30
  98%     31
  99%     31
 100%     31 (longest request)                                    #所有请求花费了68毫秒

接下来将请求总数和并发数设置为 1500 ,会发现 ApacheBench 无法进行测试,出现如下提示:

root@wuychn:/# ab -n1500 -c1500 http://192.168.11.200/
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.11.200 (be patient)
socket: Too many open files (24)

该提示表示打开的文件超出了系统限制。按照 Linux 一切皆文件的理念,连接数也是文件,Linux 系统默认限制了一个进程最多打开的文件数量。通过 ulimit -a 可以查看当前系统的限制:

root@wuychn:/# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 3611
max locked memory       (kbytes, -l) 16384
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 3611
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

可以看到 open files 为 1024,,使用 ulimit -n 命令可以临时更改这个数量。若要每次开机后自动修改,可以将命令写入 /etc/profile 文件中。下面修改打开文件数量为 65535,然后重新运行 ab 命令进行测试:

root@wuychn:/# ulimit -n 65535
root@wuychn:/#
root@wuychn:/# ab -n1500 -c1500 http://192.168.11.200/
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.11.200 (be patient)
Completed 150 requests
Completed 300 requests
Completed 450 requests
Completed 600 requests
Completed 750 requests
Completed 900 requests
Completed 1050 requests
Completed 1200 requests
Completed 1350 requests
Completed 1500 requests
Finished 1500 requests


Server Software:        nginx/1.14.2
Server Hostname:        192.168.11.200
Server Port:            80

Document Path:          /
Document Length:        193 bytes

Concurrency Level:      1500
Time taken for tests:   0.564 seconds
Complete requests:      1500
Failed requests:        1499
   (Connect: 0, Receive: 0, Length: 1499, Exceptions: 0)
Non-2xx responses:      1
Total transferred:      1267010 bytes
HTML transferred:       917581 bytes
Requests per second:    2660.00 [#/sec] (mean)
Time per request:       563.909 [ms] (mean)
Time per request:       0.376 [ms] (mean, across all concurrent requests)
Transfer rate:          2194.17 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0   29  15.2     36      43
Processing:     2   75 121.9     49     471
Waiting:        1   67 123.4     30     470
Total:          3  104 128.3     87     511

Percentage of the requests served within a certain time (ms)
  50%     87
  66%     88
  75%     90
  80%     90
  90%     92
  95%    508
  98%    508
  99%    508
 100%    511 (longest request)

上述操作只更改了客户端 Linux 系统,而服务器端仍然存在限制,因此在 1500 并发连接情况下,会出现失败的请求,在 ApacheBench 的测试报告中会看到如下的信息:

Complete requests:      1500
Failed requests:        1499

可以看出,在 1500 的并发数下 Nginx 服务器出现了失败的情况,此时若查看 Nginx 的日志文件 error.log,可以看到 Too many open files 的错误记录:

为了使 Nginx 能够承载更高的并发数,可以编辑 nginx.conf 配置文件进行配置,具体如下:

worker_processes  auto;
worker_rlimit_nofile 65535;
events {
    worker_connections  65535;
    multi_accept on;
}

worker_processes 指令用于指定工作进程的个数,设置为 auto 时 Nginx 将根据 CPU 的核心数来控制;worker_rlimit_nofile 用于设置最多打开的文件数量;worker_connections 用于设置每个工作进程可接收的连接数;multi_accept 表示是否允许一个工作进程响应多个请求。

重启 Nginx,使用 ApacheBench 工具进行 2000 并发连接数测试,具体操作如下:

root@wuychn:/usr/local/nginx/logs# ab -n2000 -c2000 http://192.168.11.200/
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.11.200 (be patient)
Completed 200 requests
Completed 400 requests
Completed 600 requests
Completed 800 requests
Completed 1000 requests
Completed 1200 requests
Completed 1400 requests
Completed 1600 requests
Completed 1800 requests
Completed 2000 requests
Finished 2000 requests


Server Software:        nginx/1.14.2
Server Hostname:        192.168.11.200
Server Port:            80

Document Path:          /
Document Length:        612 bytes

Concurrency Level:      2000
Time taken for tests:   0.213 seconds
Complete requests:      2000
Failed requests:        0
Total transferred:      1690000 bytes
HTML transferred:       1224000 bytes
Requests per second:    9389.32 [#/sec] (mean)
Time per request:       213.008 [ms] (mean)
Time per request:       0.107 [ms] (mean, across all concurrent requests)
Transfer rate:          7748.02 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       47   61   8.1     59      74
Processing:    60   69   7.6     67      89
Waiting:       43   63  12.7     65      89
Total:        121  129   5.2    128     142

Percentage of the requests served within a certain time (ms)
  50%    128
  66%    133
  75%    134
  80%    135
  90%    136
  95%    138
  98%    141
  99%    142
 100%    142 (longest request)

可以看出,Nginx 完成了并发测试,没有出现失败的请求。

1.2 客户端请求限制

在完成 Nginx 连接数优化后,有一个问题值得注意,就是在真实上线环境中,如果服务器遇到同一个 IP 地址发送了 2000 个并发请求,很可能是遇到网络攻击,如果没有任何防御措施,会消耗服务器大量的资源。企业一般会通过部署专业的防火墙设备来阻挡攻击,而Nginx 本身也具有这样的功能,下面将介绍如何利用 Nginx 来对客户端的请求进行限制。

1.2.1 限制同一个 IP 的并发数

通过 limit_conn 指令可以限制并发连接数,在 nginx.conf 配置文件中进行如下配置即可:

http {
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_conn perip 10;
    ......
}

limit_conn_zone 指令用于开辟一个共享内存空间保存客户端 IP,空间名称为 perip,空间大小为 10MB;limit_conn 指令用于限制连接数量;预定义变量 $binary_remote_addr 保存了用二进制表示的当前客户端 IP 地址。上述配置生效后,Nginx 将对于同 一个 IP 地址只允许 10 个并发连接,当超过时返回 503 (服务暂时不可用)错误。另外,limit_conn 指令也可以在 server 和 location 块中使用,用于实现不同级别的控制。

在客户端使用 ApacheBench 工具进行并发测试,可以看到 100 个请求中只有 10 个是正常的(未生效?)

root@wuychn:/usr/local/nginx/logs# ab -n100 -c100 http://192.168.11.200/
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.11.200 (be patient).....done


Server Software:        nginx/1.14.2
Server Hostname:        192.168.11.200
Server Port:            80

Document Path:          /
Document Length:        612 bytes

Concurrency Level:      100
Time taken for tests:   0.009 seconds
Complete requests:      100
Failed requests:        0
Total transferred:      84500 bytes
HTML transferred:       61200 bytes
Requests per second:    11019.28 [#/sec] (mean)
Time per request:       9.075 [ms] (mean)
Time per request:       0.091 [ms] (mean, across all concurrent requests)
Transfer rate:          9093.06 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        3    4   0.3      4       5
Processing:     1    3   1.1      3       5
Waiting:        0    2   1.2      2       5
Total:          6    7   0.9      7       9

Percentage of the requests served within a certain time (ms)
  50%      7
  66%      8
  75%      8
  80%      8
  90%      8
  95%      8
  98%      8
  99%      9
 100%      9 (longest request)

1.2.2 限制虚拟主机的并发数

在使用 limit_conn_zone 指令时,也可以用共享内存空间保存虚拟主机名($server_name ),实现对虚拟主机的并发数进行限制,具体配置如下:

http {
    limit_conn_zone $server_name zone=perserver:10m;

    server {
        listen       80;
        server_name  localhost;
        limit_conn perserver 20;
        ...
    }
    ...
}

为了测试虚拟主机并发限制是否有效,将前面的 IP 并发限制取消后,在客户端使用 ApacheBench 工具进行并发测试,可以看到 100 个请求中只有 20 个是正常的(未生效?)

root@wuychn:/usr/local/nginx/logs# ab -n100 -c100 http://192.168.11.200/
This is ApacheBench, Version 2.3 <$Revision: 1807734 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 192.168.11.200 (be patient).....done


Server Software:        nginx/1.14.2
Server Hostname:        192.168.11.200
Server Port:            80

Document Path:          /
Document Length:        612 bytes

Concurrency Level:      100
Time taken for tests:   0.009 seconds
Complete requests:      100
Failed requests:        0
Total transferred:      84500 bytes
HTML transferred:       61200 bytes
Requests per second:    11228.39 [#/sec] (mean)
Time per request:       8.906 [ms] (mean)
Time per request:       0.089 [ms] (mean, across all concurrent requests)
Transfer rate:          9265.61 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        3    4   0.3      4       4
Processing:     1    3   1.1      3       5
Waiting:        0    2   1.2      2       4
Total:          5    7   0.8      7       8

Percentage of the requests served within a certain time (ms)
  50%      7
  66%      7
  75%      7
  80%      8
  90%      8
  95%      8
  98%      8
  99%      8
 100%      8 (longest request)

1.2.3 限制晌应的传输速率

Nginx 的 limit_rate 指令用于限制服务器在响应时传输数据到客户端的速率,可以在 http、server、location、location 中的 if 块中使用。下面在 http 块中进行演示,具体如下:

http {
    limit_rate 100k;
    limit_rate_after 10m;
    ...
}

在上述配置中,limit_rate 用于限制每个连接的传输速率 (每秒 100 KB);limit_rate_after 用于在已经传输指定大小的数据后再进行限速,从而实现只针对大文件限制下载速度。如果省略 limit_rate_after 指令,则无论文件大小是多少,都会进行限速。

为了测试限速是否生效,可以在站点根目录下创建一个上传一个大于10M的测试文件,然后使用 wget 命令下载,具体不再演示。

1.3 浏览器缓存优化

服务器可以通过响应消息控制浏览器缓存,和缓存相关的响应头有 Expires、Cache-Control、ETag、Last-Modified 等。其中,Last-Modified 和 ETag 由 Nginx 自动生成,前者表示最后修改的时间,后者用于浏览器判断内容有无改变;Cache-Control 比较复杂,通常根据实际需要进行控制;Expires 表示该资源的过期时间,如果没有过期则浏览器不会发起 HTTP 请求。

在优化浏览器缓存时,通常会对静态资源(如图片、css 文件、JavaScript 文件)进行优化。一个内容丰富的网页中会包含大量的静态资源,在没有浏览器缓存的情况下,每个资源都要请求服务器。由于网页中的静态资、源是不经常发生变化的,服务器可以控制静态资源的过期时间,使浏览器对于未过期的资源直接从缓存中读取,以减少请求次数,使网页整体加载速度更快。

接下来在 Nginx 配置文件中通过 expires 指令为静态资源设置过期时间,将图片、swf(Flash 动画)文件设置为 30 天后过期,将 css、js 文件设置为 12 小时后过期:

        location ~\.(gif|jpg|jpeg|png|bmp|swf)$ {
            expires 30d;
        }
        location ~\.(css|js)$ {
            expires 12h;
        }

为了测试缓存控制是否生效,在站点根目录中创建一个网页 test.html,内容如下:

<link rel="stylesheet" type="text/css" href="style.css"/>
<img src="2.jpg" width="200" height="200"/>

注意需要在同目录中放入style.css和2.jpg。

重启 Nginx,访问 http://192.168.11.200/test.html,通过开发者工具可以查看资源的过期时间:

如果此时执行刷新操作,则会看到静态资源显示为 from cache:

二、Nginx + Keepalived 高可用方案

2.1 概述

高可用(High Availability)是指通过专门的架构设计,减少整个系统的故障时间,保持其提供服务的高度可用性。在将 Nginx 作为负载均衡服务器使用时,upstream 机制能够检测出后端服务器是否可用,如果其中一台服务器宕机,Nginx 能够自动转移到后端正常的服务器中,以保持系统持续可用。

衡量一个集群的高可用性在于没有单点故障,即其中任何一台服务器若机都不会造成整个服务中断。若一个集群在前端只有一台 Nginx 反向代理负载均衡服务器,一旦该服务器发生故障,就会造成整个集群的服务中断。为了解决这个问题,可以利用 Keepalived 部署备用服务器,实现故障转移。

Keepalived 内置了 VRRP (Virtual Router Redundancv Protocol,虚拟路由冗余协议)功能,VRRP 用于解决静态路由出现的单点故障问题,它通过 IP 多播的方式通信,当发现主路由故障时,通过选举策略将备用路由更换为主路由,从而继续提供服务。

Keepalived 利用 VRRP 实现了将提供对外访问的 IP 地址(Virtual IP)自动在主服务器(Master)和备用服务器(Backup)之间切换,正常情况下 Master 使用 Virtual IP 提供对外访问,当 Master 故障时,其他正在监控 Master 的 Backup 会通过优先级(priority)机制竞争接管 Virtual IP 继续对外提供服务,其他落选的 Backup 会继续监控当前使用的 Virtual IP 服务器。

下面搭建基于 Nginx+ Keepalived 的高可用实验环境,及其配置如下:

角色 Real IP Virtual IP 说明
Master 192.168.11.200 192.168.11.234 Nginx + Keepalived
Backup 192.168.11.201 192.168.11.234 Nginx + Keepalived
  192.168.11.100   后端服务器
  192.168.11.200   后端服务器

其中Master是一台反向代理和负载均衡服务器,对外提供访问,将请求转发的后端服务器,Backup是Master的备用机,用于在Master故障时代替,Real IP是服务器实际IP地址,Virtual IP是提供对外访问的IP。对客户端来说,通过Virtual IP访问到的服务器无论是Master还是Backup,服务都是可用的。

2.2 安装和配置 Keepalived 服务

2.2.1 部署主服务器

在 IP 为192.168.11.200 的机器上,编译安装 Nginx,更改防火墙规则允许 80 端口访问。

然后修改 Nginx 站点目录下 index.html,用于提示当前服务器身份:

root@wuychn:/usr/local/nginx/html# echo 'This is Master Server' > index.html

访问测试:

2.2.2 安装 Keepalived

Keepalived 官网下载安装包,上传到 /opt/apps目录下,执行如下操作安装:

root@wuychn:/opt/apps# tar -xvzf keepalived-2.0.16.tar.gz
root@wuychn:/opt/apps# cd keepalived-2.0.16/
root@wuychn:/opt/apps/keepalived-2.0.16# ./configure

注意,执行 ./configure 后,在输出信息中确保:

Use VRRP Framework       : Yes
Use VRRP VMAC            : Yes
Use VRRP authentication  : Yes

之后执行:

root@wuychn:/opt/apps/keepalived-2.0.16# make && make install

安装完成后,添加到系统服务(还应配置开启自启动):

root@wuychn:/usr/local/etc/sysconfig# cd /usr/local/etc/sysconfig/
root@wuychn:/usr/local/etc/sysconfig#
root@wuychn:/usr/local/etc/sysconfig# cp keepalived /etc/init.d/keepalived
root@wuychn:/usr/local/etc/sysconfig#
root@wuychn:/usr/local/etc/sysconfig# chmod +x /etc/init.d/keepalived

2.2.3 配置主服务器的 Keepalived

启动 Keepalived 前需要创建一个配置文件,Keepalived 将会根据配置文件中的配置进行工作。执行如下命令可以查看 Keepalived 的配置文件模板,该文件中提供了一些参考配置:

root@wuychn:/usr/local/etc/sysconfig# less /usr/local/etc/keepalived/keepalived.conf

在 Keepalived 服务脚本中,默认加载的配置文件路径为 /etc/keepalived/keepalived.conf,目前该文件并不存在,需要手动创建,具体操作步骤如下:

root@wuychn:~# mkdir /etc/keepalived
root@wuychn:~#
root@wuychn:~# touch /etc/keepalived/keepalived.conf

keepalived.conf 内容如下:

vrrp_instance VI_1 {              #配置一个虚拟路由,名称为 VI_1
    state MASTER                  #指定keepalived的角色,MASTER或BACKUP
    interface ens33               #指定监测的网卡
    virtual_router_id 51          #虚拟路由的标识,同一个VRRP的MASTER和BACKUP应一致
    #mcast_src_ip 192.168.11.200   #设置Real IP(可以省略,默认使用网卡的主IP)
    priority 100                  #优先级、权重(权重最高的主机将接管Virtual IP)范围0~254
    advert_int 1                  #MASTER和BACKUP之间同步检查的时间间隔,单位秒
    authentication {              #设置验证类型和密码
        auth_type PASS            #验证类型,PASS表示使用密码验证
        auth_pass 1111            #验证密码,用于MASTER和BACKUP之间使用相同密码通信
    }
    virtual_ipaddress {           #设置虚拟IP,每行一个 
        192.168.11.234            
    }
}

完成上述文件的编写后,即可启动 Keepalived 服务,并检查配置是否生效:

root@wuychn:~# service keepalived start
root@wuychn:~#
root@wuychn:~# ps -ef | grep keepalived
root      14878      1  0 17:45 ?        00:00:00 /usr/local/sbin/keepalived -D
root      14880  14878  0 17:45 ?        00:00:00 /usr/local/sbin/keepalived -D
root      14887  14711  0 17:45 pts/0    00:00:00 grep --color=auto keepalived
root@wuychn:~#
root@wuychn:~# ip a | grep 192.168.11.234
    inet 192.168.11.234/32 scope global ens33

其中,ip a | grep 192.168.11.234 用于查看 Keepalived 添加的虚拟 IP。

在 Keepalived 启动后,就可以使用虚拟 IP 地址 192.168.11.234 访问 Nginx:

2.2.4 配置备用服务器的 Keepalived

基于主服务器克隆出一台备用服务器,将 IP 地址配置为 192.168.11.201,然后打开 Keepalived 配置文件,将服务器身份更改为 BACKUP,并降低优先级,具体修改如下:

vrrp_instance VI_1 {              #配置一个虚拟路由,名称为 VI_1
    state BACKUP                  #指定keepalived的角色,MASTER或BACKUP
    interface ens33               #指定监测的网卡
    virtual_router_id 51          #虚拟路由的标识,同一个VRRP的MASTER和BACKUP应一致
    #mcast_src_ip 192.168.11.201   #设置Real IP(可以省略,默认使用网卡的主IP)
    priority 90                   #优先级、权重(权重最高的主机将接管Virtual IP)范围0~254
    advert_int 1                  #MASTER和BACKUP之间同步检查的时间间隔,单位秒
    authentication {              #设置验证类型和密码
        auth_type PASS            #验证类型,PASS表示使用密码验证
        auth_pass 1111            #验证密码,用于MASTER和BACKUP之间使用相同密码通信
    }
    virtual_ipaddress {           #设置虚拟IP,每行一个 
        192.168.11.234            
    }
}

注意,Master 和 Backup 服务器中的 Keepalived 通过 VRRP 的 112 端口通信,若端口无法访问则会同时抢占 Virtual IP 地址,所以需要为两台服务器配置防火墙规则,开放 112 端口。

完成上述配置后,执行 service keepalived start 启动 Backup 服务器的 Keepalived 服务。为了区分当前访问到的是哪一台服务器,在备用服务器中修改 index.html 文件:

This is Backup Server

之后启动 Backup 的 Nginx。

通过浏览器访问 http://192.168.11.234/ 进行测试。由于 Master 的优先级高于 Backup 的优先级,因此访问到的一直是 Master 服务器。当关闭 Master 后,再次访问就会看到网页内容变为 This is Backup,说明当前 Backup 已经接管成功。

再次开启 Master 后,访问结果又会变为 This is Master,这是因为 Master 能够抢占 Backup 接管的 Virtual IP。

另外, Keepalived 还可以配置多台 Backup 服务器,从而进一步提高服务的可用性。

2.3 使用 Keepalived 监控 Nginx 服务

使用 Keepalived 除了可以监控其他服务器中的 Keepalived 是否正常,也可以监控本机中的某个服务是有正常。下面将实现利用 Keepalived 监控 Nginx 进程是否正常工作,如果 Nginx 出现问题,则尝试重新启动 Nginx。如果重启 Nginx 后仍然无法工作,则停止本机的 Keeplived 服务,从而使其他备用服务器自动接管 Virtual IP。

2.3.1 自动监控 Nginx

在 Master 和 Backup 服务器中修改 Keepalived 配置文件,编写内容如下:

vrrp_script chk_nginx {                           #配置用于检测Nginx运行状态的脚本,注意写在vrrp_instance VI_1前面,否则不会执行
    script "/etc/keepalived/chk_nginx.sh"         #脚本路径,使用绝对路径
    interval 2                                    #每2秒执行一次
    weight -20                                    #当检测失败时,权重发生的变化 	
}

vrrp_instance VI_1 {                              #配置一个虚拟路由,名称为 VI_1

    ......

    track_script {                                #添加监控脚本
        chk_nginx
    }
}

接下来执行 vi /chk_ nginx.sh 命令创建监控脚本,内容如下(注意空格!):

#!/bin/bash
if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
	nginx
	sleep 2
	if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
		service keepalived stop
	fi
fi

上述代码中第 2 行判断当前 Nginx 进程数量是否为 0,为 0 表示 Nginx 没有启动,则执行第 3 行的命令启动 Nginx,然后等待 2 秒后再次检测 Nginx 是否启动,如果仍然没有启动则停止 Keepalived 服务。

完成上述脚本编写后,为脚本设置可执行权限,然后重新加载配置:

root@wuychn:/etc/keepalived# chmod +x chk_nginx.sh
root@wuychn:/etc/keepalived#
root@wuychn:/etc/keepalived# service keepalived reload

2.3.2 Nginx + Keepalived 高可用测试

为了测试 Keepalived 是否能够实现 Nginx 服务的高可用,下面通过手动停止 Nginx 服务的方式进行验证。

首先停止 Nginx 服务:

root@wuychn:# killall nginx

等待 2 秒后,查看 Nginx 是有已经恢复启动:

root@wuychn:/etc/keepalived# ps -ef | grep nginx
root      10582  10167  0 10:34 ?        00:00:00 /bin/bash /etc/keepalived/chk_nginx.sh
root      10587      1  0 10:34 ?        00:00:00 nginx: master process nginx
nobody    10589  10587  0 10:34 ?        00:00:00 nginx: worker process
root      10591   8251  0 10:34 pts/0    00:00:00 grep --color=auto nginx

可以看出,Keepalived 能够检测出 Nginx 已经停止,并自动恢复。

如果 Nginx 没有被 Keepalived 启动,可以查看 Keepalived 的日志,Keepalived 的日志默认打在系统日志中,可以使用 grep 过滤一下:

cat /var/log/syslog | grep Keepalived

接下来测试当 Nginx 无法重新启动时,Keepalived 能否将 Virtual IP自动切换到备用服务器。首先保证在正常情况下浏览器访问 http://192.168.11.234/ 看到的是 "This is Master Server",然后在主服务器中执行如下命令停止 Nginx 服务并立即取消 Nginx 程序的可执行权限。具体操作如下:

首先创建停止 Nginx 服务并立即取消 Nginx 程序可执行权限的脚本:

root@wuychn:/etc/keepalived# cd /usr/local/nginx/sbin/
root@wuychn:/usr/local/nginx/sbin#
root@wuychn:/usr/local/nginx/sbin# vi test.sh
root@wuychn:/usr/local/nginx/sbin#
root@wuychn:/usr/local/nginx/sbin# chmod +x test.sh

其中,test.sh 的内容如下:

#!/bin/bash
killall nginx
chmod -x nginx

之后,执行 test.sh 脚本:

root@wuychn:/usr/local/nginx/sbin# ./test.sh

执行上述命令后,通过浏览器访问进行测试,若网页显示的结果变为 "This is Backup Server",说明当前已经自动切换到备用服务器,Nginx + Keepalived 高可用环境已经部署完成。

 

发布了114 篇原创文章 · 获赞 91 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qmqm011/article/details/89963148