nginx安装参考:https://blog.csdn.net/qq_38270106/article/category/9339417
1.下载keepalived
cd /usr/local && wget http://www.keepalived.org/software/keepalived-1.2.18.tar.gz
2.解压安装:
tar -zxvf keepalived-1.2.18.tar.gz -C /usr/local/
3.下载插件openssl(需要安装一个软件包)
yum install -y openssl openssl-devel
4.开始编译keepalived
cd keepalived-1.2.18/ && ./configure --prefix=/usr/local/keepalived
make && make install
如果报错: eepalived执行./configure --prefix=/usr/local/keepalived时报错:configure: error: Popt libraries is required
出现此错误的原因:
未安装popt的开发包
解决方法:
yum install popt-devel
安装好popt的开发包。重新./configure 即可。
5.keepalived安装成Linux系统服务
将keepalived安装成Linux系统服务,因为没有使用keepalived的默认安装路径(默认路径:/usr/local),安装完成之后,需要做一些修改工作:
首先创建文件夹,将keepalived配置文件进行复制:
mkdir /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/
然后复制keepalived脚本文件:
cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
ln -s /usr/local/sbin/keepalived /usr/sbin/
ln -s /usr/local/keepalived/sbin/keepalived /sbin/
可以设置开机启动:chkconfig keepalived on,到此我们安装完毕!
-
keepalived 常用命令
service keepalived start
service keepalived restart
service keepalived stop
如果启动报错Starting keepalived (via systemctl): Job for keepalived.service failed. See 'systemctl status keepalived.service' and 'journalctl -xn' for details.
解决办法
cd /usr/sbin/
rm -f keepalived
cp /usr/local/keepalived/sbin/keepalived /usr/sbin/
6.使用keepalived虚拟VIP
cd /etc/keepalived
rm -rf keepalived.conf
vi keepalived.conf
! Configuration File for keepalivedvrrp_script chk_nginx {script "/etc/keepalived/nginx_check.sh" #运行脚本,脚本内容下面有,就是起到一个nginx宕机以后,自动开启服务interval 2 #检测时间间隔weight -20 #如果条件成立的话,则权重 -20
}# 定义虚拟路由,VI_1 为虚拟路由的标示符,自己定义名称
vrrp_instance VI_1 {state MASTER # MASTER 主的意思 BACKUP 从interface ens33 # 绑定虚拟 IP 的网络接口,根据自己的机器填写virtual_router_id 121 # 虚拟路由的 ID 号,随便定义一个数字, 两个节点ID号必须一样mcast_src_ip 192.168.128.152 #填写本机ippriority 100 # 节点优先级,主要比从节点优先级高nopreempt # 优先级高的设置 nopreempt 解决异常恢复后再次抢占的问题advert_int 1 # 组播信息发送间隔,两个节点设置必须一样,默认 1sauthentication {auth_type PASSauth_pass 1111}# 将 track_script 块加入 instance 配置块track_script {chk_nginx #执行 Nginx 监控的服务}### 虚拟IP地址配置规范 跟本机IP同一网段virtual_ipaddress {192.168.128.100 # 虚拟ip,也就是解决写死程序的ip怎么能切换的ip,也可扩展,用途广泛。可配置多个。}
}
注意:克隆一台BACKUP虚拟机,需要把state改成BACKUP,和修改ip地址即可
7.配置重启nginx的脚本
vi /etc/keepalived/nginx_check.sh
放入以下内容:
#!/bin/bash
A=`ps -C nginx ¨Cno-header |wc -l`
if [ $A -eq 0 ];then/usr/local/nginx/sbin/nginxsleep 2if [ `ps -C nginx --no-header |wc -l` -eq 0 ];thenkillall keepalivedfi
fi
赋权:
chmod 755 /etc/keepalived/nginx_check.sh
8.启动nginx和keepalived
/usr/local/nginx/sbin/nginx
service keepalived start
ip addr查看,虚拟出来了一个IP
访问nginx主页
访问虚拟IP主页