作者:冉南阳
简介
本文通过Keepalived服务vip漂移的方式配置Nginx的高可用;当vip所在节点的Nginx服务宕掉后,会将vip漂移到另外一个节点。而在配置Nginx的配置时,分别在两个节点配置Nginx服务,然后两个Nginx服务配置相同的负载均衡等配置;在配置连接时不使用两个Nginx节点的ip,而是使用vip; 以这样的方式实现Nginx的高可用。
Nginx安装
在两个节点同时安装Nginx,此处展示一个节点
下载安装包
wget http://nginx.org/download/nginx-1.12.2.tar.gz
解压并进行编译安装,默认安装目录为/usr/local/nginx
tar -zxf nginx-1.12.2.tar.gz
cd nginx-1.12.2
./configure --with-stream
make && make install
添加到systemctl启动项
编写脚本/usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
[Install]
WantedBy=multi-user.target
将服务添加到开机自启动
systemctl enale nginx
systemctl start nginx
systemctl status nginx
此处修改端口为8089,默认端口为80;配置文件默认在/user/local/nginx/conf/nginx.conf
启动成功
安装Keepalived
两个节点都安装
yum -y install keepalived
添加到开机自启动
配置HA
1.两个节点同时配置
编辑脚本/etc/keepalived/nginx_check.sh,脚本内容如下(nginx _check.sh),两个节点都需要该脚本。
#!/bin/bash
A=`ps -C nginx --no-header | wc -l`
if [ $A -eq 0 ];then
/etc/init.d/nginx start
sleep 3
if [ `ps -C nginx --no-header | wc -l ` -eq 0 ];then
/etc/init.d/nginx stop
fi
fi
增加执行权限
chmod +x /etc/keepalived/nginx_check.sh
2.节点cdh234.macro.com配置Keepalived
修改配置文件/etc/keepalived/keepalived.conf,配置vip为192.168.0.245
启动Keepalived服务
systemctl start keepalived
vip已绑定成功
cdh235.macro.com节点ping 192.168.0.245
停止Keepalived服务后查看192.168.0.245已从网卡ens192解绑
3.节点cdh235.macro.com配置Keepalived
修改配置文件/etc/keepalived/keepalived.conf,配置vip为192.168.0.245
启动Keepalived服务
systemctl start keepalived
vip已绑定成功
cdh234.macro.com节点ping 192.168.0.245
验证Keepalived服务IP漂移
两个节点同时起Keepalived
只有其中一个节点cdh235.macro.com绑定了vip 192.168.0.245
停止cdh235.macro.com的服务Keepalived,cdh235.macro.com解绑vip,cdh234.macro.com绑定vip
验证Nginx的高可用
vip绑定在cdh234.macro.com节点上
使用vip:8089访问nginx的web界面成功
停止cdh234.macro.com节点的nginx,vip已没有绑定;vip 绑定到节点cdh235.macro.com
依然可以访问