实施过程:
测试准备四台机器每台机器都安装好nginx
两台做代理 两台做真实服务器
给两台代理服务器安装keepalived制作高可用集群,生成VIP
配置nginx的负载均衡
两台nginx服务器配置文件一致
根据站点分区进行调度
配置upstream文件
在两台代理机器操作:192.168.239.128 192.168.239.129
vim /etc/nginx/conf.d/default.conf
upstream index {
server 192.168.239.130:80 weight=1 max_fails=2 fail_timeout=2;
server 192.168.239.131:80 weight=2 max_fails=2 fail_timeout=2;
}
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/host.access.log main;
location / {
proxy_pass http://index;
proxy_redirect default;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
将nginx配置文件拷贝到另一台代理服务器中:
scp /etc/nginx/conf.d/default.conf 192.168.239.129:/etc/nginx/conf.d/
俩台机子 curl测试一下
[root@localhost ~]# curl 192.168.239.128
[root@localhost ~]# curl 192.168.239.129
主/备调度器安装软件
yum -y install keepalived
主操作:
mv /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id directory1 #辅助改为directory2 #识别id
}
vrrp_instance VI_1 {
state MASTER #定义主还是备
interface ens33 #VIP绑定接口
virtual_router_id 80 #整个集群的调度器一致 #集群id号
priority 100 #优先级,backup改为50
advert_int 1 #心跳检测的时间间隔1s
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.239.16/24 #设置vip
}
}
备操作:
mv /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf.bak
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id directory2
}
vrrp_instance VI_1 {
state BACKUP #设置为backup
interface ens33 #产生网卡放在哪里
nopreempt #设置到back上面,不抢占资源(VIP)
virtual_router_id 80 #id和master一致
priority 50 #辅助改为50
advert_int 1 #检测间隔1s
authentication { #密码
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.239.16/24 #和master vip一致
}
}
启动两台keepalived
systemctl start keepalived
ip a 查看
对调度器Nginx健康检查(可选)两台都设置
思路:
让Keepalived以一定时间间隔执行一个外部脚本,脚本的功能是当Nginx失败,则关闭本机的Keepalived
(1)写一个脚本script
vim /etc/keepalived/check_nginx_status.sh
#!/usr/bin/bash
/usr/bin/curl 192.168.239.128 &>/dev/null
if [ $? -ne 0 ]
then
systemctl stop keepalived
fi
chmod +x /etc/keepalived/check_nginx_status.sh
(2) keepalived使用脚本
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
router_id directory1
}
vrrp_script check_nginx { #添加
script "/etc/keepalived/check_nginx_status.sh" #脚本路径
interval 5
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 80
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.246.16/24
}
track_script { #添加
check_nginx
}
}
注:必须先启动Nginx,再启动keepalived
测试访问:
将keepalived集群的主节点的Nginx服务关闭,查看vip是否漂移,如果漂移,即成功