keepalived 类似的还有 lvs
nginx 我的已经安装好, 安装步骤: https://blog.csdn.net/tang_jian_dong/article/details/83995676
我的keepalived版本是 2.0.15
两台虚拟机各自安装 nginx 与 keepalived
如果安装nginx 时 安装了如下依赖则安装 keppalived 不需要安装, 如果没有安装则需要安装如下依赖
出现这种错误则是依赖没有安装完整,
安装依赖:
yum -y install gcc pcre-devel zlib-devel openssl openssl-devel libssl-dev libnl-devel
下载keepalived的方式:
一:
yum install -y keepalived
二:
keepalived 官网: https://www.keepalived.org/download.html
下载如下 keepalived , 上传至liunx。
1:进入 keepalived 目录, 解压: tar -zxvf keepalived-2.0.15.tar.gz
2: 进入 keepalived-2.0.15, 命令: cd keepalived-2.0.15
3: 安装: ./configure --prefix=/usr/local/keepalived
出现如下界面则安装成功。
4:在当前目录下执行: make && make install
5: 配置keepalived服务
cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
mkdir /etc/keepalived //这是keepalived默认加载配置文件的路径
cp /usr/local/keepalived/etc/keepalived/keepalived.conf/etc/keepalived/
6: 将keepalived 加入开机启动
systemctl enable keepalived.service 或者 chkconfig keepalived on
7: 准备 nginx 启动脚本, 下面脚本的意思是:
首先获取nginx的 进程数, 如果为0 则启动nginx, 在等待两秒后再次查询一次, 如果还是为0 则停止 keepalived
1: touch nginx_check.sh 创建一个文件, 将下面命令复制进去。 将文件放在 /etc/keepalived 此目录与配置文件一个文件夹
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
2: 给创建的文件赋权。
chmod +x nginx_check.sh
8: 修改 /etc/keepalived/keepalived.conf 文件 ,命令: vim /etc/keepalived/keepalived.conf
将原文件内容清空,将下列命令复制进去,
global_defs {
router_id 129 #标识节点的字符串,通常为hostname
}
vrrp_script chk_nginx {
script "/etc/keepalived/nginx_check.sh" #运行脚本,脚本内容下面有,就是起到一个nginx宕机以后,自动开启服务
interval 2 #检测时间间隔
weight -20 #如果条件成立的话,则权重 -20
}
# 定义虚拟路由,VI_1 为虚拟路由的标示符,自己定义名称
vrrp_instance VI_1 {
state BACKUP #来决定主从 MASTER BACKUP 两种
interface ens33 # 绑定虚拟 IP 的网络接口,根据自己的机器填写 ip a 查看
virtual_router_id 129 # 虚拟路由的 ID 号
mcast_src_ip 192.168.xx.xx #填写本机ip
priority 100 # 节点优先级,主要比从节点优先级高
nopreempt # 优先级高的设置 解决异常恢复后再次抢占的问题, master挂掉,backup升级为master,原master为backup
advert_int 1 # 组播信息发送间隔,两个节点设置必须一样,默认 1s
authentication { #pass ah 推荐使用 pass
auth_type PASS
auth_pass 1111
}
# 将 track_script 块加入 instance 配置块
track_script {
chk_nginx #执行 Nginx 监控的服务
}
virtual_ipaddress {
192.168.xx.xx # 虚拟ip,也就是解决写死程序的ip怎么能切换的ip,也可扩展,用途广泛。可配置多个。
}
}
~
~
service keepalived start //启动 keepalived
service keepalived stop //停止 keepalived
//keepalived加入开机启动
systemctl enable keepalived.service 或者 chkconfig keepalived on
9: 测试;
启动nignx
1:cd /usr/local/nginx/html
2: vim index.html 在如下添加ip 或者标识
3: 浏览器访问niginx
10 查看 keepalived: 启动 service keepalived start
命令: ip a
如下就是配置的 虚拟ip
在浏览器 中访问虚拟ip
将其他 keepalived 停止, 在浏览器再次访问虚拟ip ,则会发现 已经访问不通。
此时nginx 还是能访问的:
将nginx 停掉: 命令: pkill nginx
此时 nginx 无法访问
启动 keepalived
service keepalived start
会发现 nginx 与 虚拟ip 都能访问了
集群测试: 启动两台虚拟机的 nginx 与 keepalived
我启动 128 与 130 ,访问虚拟ip 192.168.10.150
访问虚拟ip,
停掉 128
命令: stop keepalived.service
此时再次访问虚拟ip 192.168.10.150, 会发现 nginx已经切到 130