服务器准备:
虚拟IP(VIP):
在两台服务器上执行:
# 对于CentOS/RHEL系统
yum install -y nginx keepalived
# 对于Ubuntu/Debian系统
apt-get install -y nginx keepalived
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/usr/bin/killall -0 nginx" # 检查nginx进程是否存在
interval 2 # 每2秒检查一次
weight 2 # 权重
}
vrrp_instance VI_1 {
state MASTER # 主服务器设置为MASTER
interface eth0 # 网卡名称,根据实际情况修改
virtual_router_id 51 # 虚拟路由ID,主备必须相同
priority 100 # 优先级,主服务器应高于备服务器
advert_int 1 # 检查间隔,单位秒
authentication {
auth_type PASS
auth_pass 1111 # 认证密码,主备必须相同
}
virtual_ipaddress {
192.168.1.100/24 # 虚拟IP地址,根据实际情况修改
}
track_script {
chk_nginx # 引用上面定义的nginx检查脚本
}
}
! Configuration File for keepalived
global_defs {
router_id LVS_DEVEL
}
vrrp_script chk_nginx {
script "/usr/bin/killall -0 nginx"
interval 2
weight 2
}
vrrp_instance VI_1 {
state BACKUP # 备服务器设置为BACKUP
interface eth0 # 网卡名称,根据实际情况修改
virtual_router_id 51 # 必须与主服务器相同
priority 90 # 优先级低于主服务器
advert_int 1
authentication {
auth_type PASS
auth_pass 1111 # 必须与主服务器相同
}
virtual_ipaddress {
192.168.1.100/24 # 虚拟IP地址,与主服务器相同
}
track_script {
chk_nginx
}
}
在两台服务器上配置相同的Nginx服务,确保服务可用性。
示例配置 (/etc/nginx/nginx.conf):
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
}
在两台服务器上执行:
systemctl start nginx
systemctl enable nginx
systemctl start keepalived
systemctl enable keepalived
检查虚拟IP是否绑定在主服务器上:
ip addr show eth0
应该能看到虚拟IP(192.168.1.100)绑定在主服务器的eth0网卡上
模拟主服务器故障:
bash
systemctl stop nginx
恢复主服务器:
bash
systemctl start nginx
虚拟IP不漂移:
virtual_router_id
和auth_pass
一致Nginx检查脚本不工作:
chmod +x /path/to/script
日志查看:
journalctl -u keepalived -f
tail -f /var/log/messages
邮件通知:
在global_defs
部分添加:
global_defs {
notification_email {
admin@example.com
}
notification_email_from keepalived@example.com
smtp_server 127.0.0.1
smtp_connect_timeout 30
}
多VIP配置:
可以在virtual_ipaddress
部分添加多个VIP:
virtual_ipaddress {
192.168.1.100/24
192.168.1.101/24
}
更复杂的健康检查:
可以修改chk_nginx
脚本为更复杂的检查:
vrrp_script chk_nginx {
script "/usr/bin/curl -s http://localhost/health-check > /dev/null"
interval 2
timeout 2
fall 2
rise 2
}
通过以上配置,您已经建立了一个高可用的Nginx服务,当主服务器出现故障时,备服务器会自动接管服务,确保服务的持续可用性。