下面内容整理自bilibili-尚硅谷-Nginx青铜到王者视频教程
Nginx相关文章
Nginx入门到精通一(基本概念介绍)-CSDN博客
Nginx入门到精通二(安装配置)-CSDN博客
Nginx入门到精通三(Nginx实例1:反向代理)-CSDN博客
Nginx入门到精通四(反向代理2)-CSDN博客
Nginx入门到精通六(高可用配置)-CSDN博客
Nginx入门到精通七(Nginx原理)-CSDN博客
========================================================
高可用介绍
正常访问的时候,由Master负责处理请求,当master挂掉的时候,由备份服务器处理请求;
准备工作
1, 准备2台Nginx服务器;192.168.10.128 和 192.168.10.130
2, 2台Nginx中安装Keepalived:yum install -y keepalived
验证keepalived:rpm -q -a keepalived
3, 虚拟IP:192.168.10.10
高可用配置
编辑配置文件:/etc/keepalived/keepalived.conf
Master配置
! Configuration File for keepalived
global_defs {
notification_email { # 告警通知的邮件地址信息
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc #邮件发件人
smtp_server 192.168.10.128 # smtp地址,设为本地地址
smtp_connect_timeout 30 # smtp超时时间
router_id LVS_DEVEL # 本地的host那么,要和hosts文件中红一致;
}
vrrp_script chk_http_port { #脚本检测块,用于设置一个自定义的健康检查脚本,该脚本用于监控HTTP服务端口的状态
script "/usr/local/src/nginx_check.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER #角色: MASTER/BACKUP
interface ens33 #网卡
virtual_router_id 51 #路由ID,主从要保持一致
priority 100 # 优先级,主库优先级高于从库
advert_int 1 # BACKUP将每秒钟发送一次VRRP广告报文和MASTER同步
authentication { # 密码校验
auth_type PASS
auth_pass 1111
}
virtual_ipaddress { # 虚拟IP地址
192.168.10.10
}
}
Backup配置
! Configuration File for keepalived
global_defs {
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.10.130
smtp_connect_timeout 30
router_id LVS_DEVEL
}
vrrp_script chk_http_port {
script "/usr/local/src/nginx_check.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.10.10
}
}
脚本配置
编辑:/usr/local/src/nginx_check.sh 脚本
脚本内容如下,检查nginx进程是否存活,如果不存活则启动nginx,如果启动失败则关闭keepalived;
[root@docker01 nginx]# cat /usr/local/src/nginx_check.sh
#!/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
启动Nginx和Keepalive
keepalived启动命令:systemctl start keepalived.service
启动后,在MASTER上通过`ip a` 可以查看虚拟IP的绑定关系;BACKUP上没有,因为此时虚拟IP绑定的是MASTER
测试验证
1, 访问VIP:192.168.10.10 走MASTER,可以正常访问;
2, 将MASTER手动停止,模拟MASTER故障的情况;
停止keepalived 和Nginx,并验证
systemctl stop keepalived.service
/usr/local/nginx/sbin/nginx -s stop
停止MASTER后依然访问192.168.10.10 访问,此时走的BACKUP
4, 此时再把MASTER 的keepalived和nginx拉起,请求又回到MASTER
配置说明
我在实际操作过程中遇到如下问题,可能是由于环境导致
1,keepalived日志查看 journalctl -u keepalived.service
2, 在主备上创建keepalive账户,并授权。不用设置密码;如果没有创建会报错
WARNING - default user ‘keepalived_script‘ for script execution does not exist - please
useradd -m keepalived_script,这是keepalive默认执行命令的账户
chown -R keepalived_script.keepalived_script /etc/keepalived/