这是详细的步骤来在 CentOS 7 上安装 nginx
和配置 keepalived
。
主服务器(IP: 192.168.9.195)
安装 Nginx
-
安装 EPEL 仓库:
sudo yum install epel-release -y
-
安装 Nginx:
sudo yum install nginx -y
-
启动 Nginx 服务并设置开机自启:
sudo systemctl start nginx sudo systemctl enable nginx
-
配置防火墙以允许 HTTP 和 HTTPS 通行(如果有防火墙):
sudo firewall-cmd --permanent --zone=public --add-service=http sudo firewall-cmd --permanent --zone=public --add-service=https sudo firewall-cmd --reload
安装 Keepalived
-
安装 Keepalived:
sudo yum install keepalived -y
-
配置 Keepalived(编辑
/etc/keepalived/keepalived.conf
):vrrp_instance VI_1 {state MASTERinterface eth0 # 根据实际情况替换为正确的网络接口用ifconfig查看virtual_router_id 51priority 100 # 主服务器优先级更高advert_int 1authentication {auth_type PASSauth_pass 1111 # 保持简单的密码用于认证}virtual_ipaddress {192.168.9.200 # 预设的虚拟 IP 地址} }
保存并关闭文件。
-
启动 Keepalived 服务并设置开机自启:
sudo systemctl start keepalived sudo systemctl enable keepalived
从服务器(IP: 192.168.9.183)
重复上述的 Nginx 安装步骤。
安装 Keepalived
-
安装 Keepalived:
sudo yum install keepalived -y
-
配置 Keepalived(编辑
/etc/keepalived/keepalived.conf
):vrrp_instance VI_1 {state BACKUPinterface eth0 # 根据实际情况替换为正确的网络接口用ifconfig查看virtual_router_id 51priority 50 # 从服务器优先级更低advert_int 1authentication {auth_type PASSauth_pass 1111 # 保持简单的密码用于认证}virtual_ipaddress {192.168.9.200 # 与主服务器相同的虚拟 IP 地址} }
保存并关闭文件。
-
启动 Keepalived 服务并设置开机自启:
sudo systemctl start keepalived sudo systemctl enable keepalived
验证配置
-
检查 Nginx 状态:
sudo systemctl status nginx
-
检查 Keepalived 状态:
sudo systemctl status keepalived
-
从另一台机器上尝试 ping 虚拟 IP 地址:
ping 192.168.9.200
确保回应来自于主服务器。
-
停止主服务器上的 Keepalived 服务,并再次尝试 ping 虚拟 IP,确认此时回应来自于从服务器:
sudo systemctl stop keepalived ping 192.168.9.200
-
重启主服务器上的 Keepalived 服务,并确认虚拟 IP 重新回到主服务器:
sudo systemctl start keepalived ping 192.168.9.200
确保在这个过程中,你的 nginx
服务是运行的,以便可以处理通过虚拟 IP 地址接收的