nginx+keepalived实现高可用集群
实验环境:
两台调度器,一主一备
192.168.200.111
192.168.200.112
两台web服务器
192.168.200.113
192.168.200.114
利用keepalived实现主备的故障切换,从而交替提供服务
利用nginx实现负载均衡的调度
配置主调度器:
1.安装依赖包
yum -y instsall ipvsadm keepalived
2.将配置文件进行备份,避免出错
cd /etc/keepalived
cp keepalived.conf keepalived.con.bak
3.编辑配置文件
vim keepalived.conf
#全局配置
notification_email {
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id LVS_MASTER
}
script "/opt/chk_nginx.sh"
interval 2
weight -20
}
state MASTER
interface eno16777728
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.254
}
track_script {
check_nginx #引用nginx脚本
}
}
4.安装nginx服务
(1.)源码安装,参考nginx安装的博客文章
(2.)软件包安装,参考fpm制作rpm包的博客文章
5.修改nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
红色字体添加内容:
keepalive_timeout 65;
upstream httpd_server {
server 192.168.200.113 weight=1;
server 192.168.200.114 weight=1;
}
server {
listen 80;
server_name localhost;
charset utf-8;
location / {
root html;
index index.html index.htm;
proxy_pass http://httpd_server;
proxy_set_header Host $http_host;
}
6.配置完成后启动服务
systemctl start keepalived
7.查看VIP端口
ip a
8.查看调度服务
ipvsadm -Ln
9.将主配置文件发送给备调度器,修改相应内容
scp /etc/keepalived/keepalived.conf 192.168.200.112:/etc/keepalived/
10.编辑nginx脚本文件,配置为周期性任务
mkdir /shell
vim /shell/nginx_check.sh
编辑内容:
#!/bin/bash
count="$(ps -C nginx --no-header|wc -l)"
if [ $count -eq 0 ];then
nginx
sleep 2
if [ `ps -c nginx --no-header` |wc -l -eq 0 ];then
systemctl stop keepalived
fi
fi
11.给脚本添加执行权限
chmod +x /shell/nginx_check.sh
配置节点服务器:
1.安装apache服务
yum -y install httpd
2.添加路由
ifconfig lo:0 192.168.200.254 netmask 255.255.255.255
route add -host 192.168.200.254 dev lo:0
3.创建测试网页
echo "11111" > /var/www/html/index.html
4.启动apache服务
systemctl start httpd
5.修改配置文件
vim /etc/sysctl.conf
添加内容;
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.default.arp_ignore = 1
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.lo.arp_ignore = 1
net.ipv4.conf.lo.arp_announce = 2
6.加载配置信息
sysctl -p
##每台节点服务器都要进行相同的配置
实验测试:
1.关闭所有服务器的防火墙和Linux安全机制
iptables -F
systemctl stop firewalld
setenforce 0
2.在浏览器中输入虚拟服务器的IP地址
这里我们用的是192.168.200.254
实现轮询的结果
3.关掉nginx和keepalived进行高可用测试
killall -9 nginx
systemctl stop keepalived
while :
> do
> curl 192.168.200.254
> sleep 1
> done
进行测试。