1、什么是 nginx高可用
只有一台nginx服务器时,如果nginx服务器宕机了,那么请求就无法访问。
要实现高可用,那就可以部署多台nginx服务器,下面以两台nginx服务器为例,示意图如下:
要配置nginx集群,至少需要满足一下条件:
(1)需要两台nginx服务器
(2)需要keepalived
(3)需要虚拟ip
2、配置高可用的Nginx集群
(1)需要两台服务器 192.168.200.130和192.168.200.131
(2)在两台服务器安装nginx
(3)在两台服务器安装keepalived
yum install keepalived -y
安装过程遇到了报错,解决方法参考:
nginx+keepalived配置踩过的坑_steven在学习的博客-CSDN博客
安装完成后查看版本信息:
安装之后,在etc里面生成目录 keepalived,有文件 keepalived.conf
(4)完成高可用配置(主从配置)
主服务器keepalived.conf配置文件内容:
! Configuration File for keepalived
global_defs {
notification_email {
[email protected]
[email protected]
[email protected]
}
notification_email_from [email protected]
smtp_server 192.168.200.130
smtp_connect_timeout 30
router_id LVS_DEVEL
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_script chk_http_port {
script "/usr/local/src/nginx_check.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MAXTER
interface ens33
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.100
}
}
从服务器keepalived.conf配置文件内容:
! Configuration File for keepalived
global_defs {
notification_email {
[email protected]
[email protected]
[email protected]
}
notification_email_from [email protected]
smtp_server 192.168.200.131
smtp_connect_timeout 30
router_id LVS_DEVEL
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
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.200.100
}
}
在主从服务器的/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和keepalived启动
启动 nginx:./nginx
启动 keepalived:systemctl start keepalived.service
查看keepalived进程
(5)最终测试
在浏览器地址栏输入虚拟ip地址192.168.200.100
能访问到nginx主页,说明配置是成功。
用ip a命令也可以看到,两台服务器都已经绑定了虚拟ip
把主服务器(192.168.200.130)nginx和keepalived停止,再输入192.168.200.100(虚拟ip)
再次查看进程
进程已经不存在了
这时候再次访问虚拟ip
这时候访问的就是从服务器(192.168.200.131)