软件环境:
OS:CentOS Linux release 7.9.2009
Nginx:V1.20.1
Keepalived:V1.3.5
OS 系统安装配置
关闭iptables
systemctl disable iptables
关闭firewalld
systemctl disable firewalld
关闭selinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled' /etc/selinux/config
** 重启服务器 **
Keepalived 配置文件-Master
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
script_user root
enable_script_security
router_id LVS_DEVEL01
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_script check_nginx {
script "/script/check_nginx_status.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 60
priority 150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.211.55.200
}
track_script {
check_nginx
}
}
Keepalived配置文件—BACKUP
vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
script_user root
enable_script_security
router_id LVS_DEVEL02
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_script check_nginx {
script "/script/check_nginx_status.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP
interface eth0
virtual_router_id 60
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.211.55.200
}
track_script {
check_nginx
}
}
Nginx健康检查脚本
#! /bin/bash
# 使用telnet Nginx的服务端口检测Nginx服务状态,状态异常停止keepalived服务
[ -x /usr/bin/telnet ] || yum install telnet -y
TMP_FILE=`mktemp telnet.XXX`
check_nginx () {
ip="nginx_ip"
port="80"
( echo -e "quit\n" | telnet $ip $port ) > $TMP_FILE
egrep '\^]' $TMP_FILE &>/dev/null
if [ $? -ne 0 ];then
killall -s QUIT nginx
systemctl start nginx
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi
}
check_nginx
rm -f /$TMP_FILE
Keepalived日志管理
# 修改keepalived文件
vim /etc/sysconfig/keepalived
# 修改配置:"KEEPALIVED_OPTIONS="-D"
KEEPALIVED_OPTIONS="-D -S 0"
# 修改CentOS rsyslog.conf文件
vim /etc/rsyslog.conf
# 添加如下配置:
local0.* /var/log/keepalived.log
# 重启rsyslog服务
service rsyslog restart
Nginx的配置文件
# 配置服务器集群
upstream web_pools {
# 开IP_hash实现客户端会议保持
ip_hash;
# 配置集群中服务器及其工作权重
server 10.211.55.5:81 weight=100 max_fails=10 fail_timeout=10s;
server 10.211.55.5:82 weight=100 max_fails=10 fail_timeout=10s;
}
server {
listen 80;
server_name localhost;
location / {
# root html;
# index index.html index.htm;
# 配置代理跳转至服务器集群
proxy_pass http://web_pools;
# 配置http请求头信息
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}