安装环境:center os7
nginx双机配置的目的是保证nginx负载均衡服务器的高可用性,防止单点故障。
nginx双机配置采用一主一备的方式,主nginx服务器绑定一个浮动IP,备nginx服务器通过脚本定时检查主服务器的nginx是否正常工作,如不在正常工作,则备nginx服务器绑定相同的服务IP,顶替主服务器。当发现主nginx恢复正常后,备nginx服务器则会解绑VIP。
- 准备一个VIP(比如:192.168.80.99 需要是同一个网段下的闲置ip)
- 配置备nginx
按照上面介绍的一台主机上的nginx简单配置在另外一台机器上配置备nginx。
- 安装keepalived(将keepalived-1.2.2.tar.gz安装包上传到服务器,例如上传目录是 /tmp)
使用root用户,运行如下命令编辑脚本:
<1>安装openssl-devel库
yum -y install openssl-devel
<2>安装Popt库
yum -y install popt-devel
<3>创建keepalived安装目录
mkdir /opt/keepalived
<4>解压安装包:tar -zxvf keepalived-1.2.2.tar.gz
<5>进入文件目录:cd keepalived-1.2.2
<6>指定安装路径安装keepalived
./configure --prefix=/opt/keepalived
make
makeinstall
<7>建立软连接
ln -s /opt/keepalived/sbin/keepalived /sbin/
ln -s /opt/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/
ln -s /opt/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
<8>修改主nginx服务器上的 /opt/keepalived/etc/keepalived/keepalived.conf 脚本
global_defs {
router_id NODEA
}
vrrp_script chk_http_port {
script "/opt/keepalived/chk_nginx_pid.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0 #监测网络接口
virtual_router_id 50 #主、备必须一样
priority 100 #优先级:主>备
advert_int 1
authentication {
auth_type PASS #VRRP认证,主备一致
auth_pass 1111 #密码
}
track_script {
chk_http_port
}
virtual_ipaddress {
192.168.80.99/24 #VRRP HA虚拟地址
}
}
<9>当检测到nginx进程宕掉后,自动关闭keepalived进程,是通过下面的脚本/opt/keepalived/chk_nginx_pid.sh 来实现的
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ]
then
echo 'nginx server is died'
service keepalived stop
fi
<10>给/opt/keepalived/chk_nginx_pid.sh加执行权限
chmod +x /opt/keepalived/chk_nginx_pid.sh
- 按照(3)的过程在备nginx服务器上安装keepalived
最后需要修改备keepalived的脚本
<1>/opt/keepalived/etc/keepalived/keepalived.conf 脚本的内容如下
global_defs {
router_id NODEA
}
vrrp_script chk_http_port {
script "/opt/keepalived/chk_nginx_pid.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0 #监测网络接口
virtual_router_id 50 #主、备必须一样
priority 90 #优先级:主>备
advert_int 1
authentication {
auth_type PASS #VRRP认证,主备一致
auth_pass 1111 #密码
}
track_script {
chk_http_port
}
virtual_ipaddress {
192.168.80.99/24 #VRRP HA虚拟地址
}
}
<2>创建脚本 /opt/keepalived/chk_nginx_pid.sh
#!/bin/bash
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ]
then
echo 'nginx server is died'
service keepalived stop
fi
<3>给/opt/keepalived/chk_nginx_pid.sh加执行权限
chmod +x /opt/keepalived/chk_nginx_pid.sh
- 分别启动主nginx服务器和备nginx服务器的keepalived
keepalived -D -f /opt/keepalived/etc/keepalived/keepalived.conf
- 如果要关闭keepalived,可以使用命令
service keepalived stop
- 启动
- 启动主nginx
登录主nginx所在服务器,使用aiuap用户,运行如下命令启动nginx:
/opt/nginx/sbin/nginx
ps -ef |grep nginx
- 启动备nginx
登录主nginx所在服务器,使用aiuap用户,运行如下命令启动nginx:
/opt/nginx/sbin/nginx
- 验证
使用浏览器访问http://<nginx的IP地址>:<nginx的端口号>/index.html,出现欢迎页面则说明配置成功。
注:使用虚拟ip替代nginx的IP地址访问效果一样