当前位置:首页 >> 服务器

keepalived+nginx高可用实现方法示例

1.keepalived介绍

keepalived最初是专为LVS负载均衡软件设计的,用来管理并监控LVS集群系统中各个服务节点的状态,后来又加入了实现高可用的VRRP功能。keepalived除了能够管理LVS软件外,还能支持其他服务的高可用解决方案。

keepalived通过VRRP协议实现高可用功能的。VRRP(Virtual Router Redundancy Protocol)虚拟路由冗余协议。VRRP出现的目的就是为了解决静态路由单点故障问题,它能保证当个别节点宕机时,整个网络可以不间断地运行。

2.keepalived高可用故障转移原理

keepalived高可用服务之间的故障转移,是通过VRRP来实现的。在keepalived服务工作时,主Master节点会不断地向备节点发送(多播的方式)心跳消息,用来告诉备Backup节点自己还活着。

  当主节点发生故障时,无法给备节点发送心跳消息,如果备节点无法继续检测到来自主节点的心跳。就会调用自身的接管程序,接管主节点的IP资源和服务。当主节点恢复时,备节点又会释放主节点故障时自身接管的IP资源和服务,恢复到原来的备用角色

3.安装nginx

3.1.主节点(192.168.80.22)

3.1.1.安装编译工具和库文件

yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel

3.1.2.安装pcre

#进入目录
cd /usr/local/develop/anginx

#上传安装文件并解压
tar -zxvf pcre-8.38.tar.gz

#进入安装目录
cd pcre-8.38

#检查配置
./configure

#编译、安装
make && make install

#查看pcre版本
pcre-config --version

3.1.3.安装nginx

#进入目录
cd /usr/local/develop/anginx
"htmlcode">
vi nginx.conf

#user nobody;
worker_processes 1;
"$request" '
           '$status $body_bytes_sent "$http_referer" '
           '"$http_user_agent" "$http_x_forwarded_for"';
"color: #ff0000">4.安装keepalived

4.1.主节点(192.168.80.22)

#安装keepalived
yum install keepalived -y
"/etc/init.d/keepalived start" /etc/rc.local
"htmlcode">
#安装keepalived
yum install keepalived -y
"/etc/init.d/keepalived start" /etc/rc.local
"color: #ff0000">5.测试

5.1.启动主备节点的keepalived服务

#在节点一执行(192.168.80.22)
/etc/init.d/keepalived start
-------------------------------------
[root@hadoop02 anginx]# ps -ef |grep keepalived
root   15788   1 0 01:09 "text-align: center">keepalived+nginx高可用实现方法示例

5.3.停止主节点keepalived服务

#在节点一执行(192.168.80.22)
/etc/init.d/keepalived stop
"text-align: center">keepalived+nginx高可用实现方法示例

6.keepalived+nginx整合

说明:编写nginx守护脚本,如果nginx服务出现故障,则停止当前节点的keepalived服务。自动切换到备用节点。

6.1.编写nginx守护脚本

vi nginx_check.sh
"htmlcode">
#停止主节点nginx服务
/usr/local/develop/anginx/webserver/nginx/sbin/nginx -s stop
​
#查找进程
[root@hadoop02 ~]# ps -ef |grep nginx
root   15915   1 0 01:51 ?    00:00:00 /bin/bash /usr/local/develop/anginx/shell/nginx_check.sh
root   16516 15753 0 01:54 pts/5  00:00:00 grep nginx
[root@hadoop02 ~]#
​
#观察备用节点变化【服务正常】
ip addr
--------------------------------------
[root@hadoop01 shell]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
  link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
  inet 127.0.0.1/8 scope host lo
  inet6 ::1/128 scope host 
    valid_lft forever preferred_lft forever
2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
  link/ether 00:50:56:38:e5:46 brd ff:ff:ff:ff:ff:ff
  inet 192.168.80.21/24 brd 192.168.80.255 scope global eth1
  inet 192.168.80.100/32 scope global eth1:1
  inet6 fe80::250:56ff:fe38:e546/64 scope link 
    valid_lft forever preferred_lft forever
[root@hadoop01 shell]#
​
#再次重新启动主节点nginx和keepalived服务
/usr/local/develop/anginx/webserver/nginx/sbin/nginx
​
/etc/init.d/keepalived start

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。