虚拟机即可,分别为:
下载地址
选择版本下载压缩包:
https://nginx.org/download/
wget命令下载:
wget https://nginx.org/download/nginx-1.22.1.tar.gz
安装后解压压缩包并进入解压目录
tar -xvf nginx-1.22.1.tar.gz
cd nginx-1.22.1
安装依赖的插件
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
配置安装目录
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
安装nginx
make && make install
安装keepalived
yum install keepalived
安装killall命令插件(重点)
yum install psmisc
进入配置文件目录
cd /usr/local/nginx/conf
vim nginx.conf
配置文件修改(只修改server部分即可)
server {
listen 8081;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /data/html;
index index.html index.htm;
}
}
写一个简单的html文件验证nginx的可用性
mkdir -p /data/html
touch index.html
vim index.html
index.html内容为(129服务器可以修改为“成功启动129”)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>成功启动131</h1>
</body>
</html>
启动nginx
cd /usr/local/nginx/sbin
./nginx
网页访问
http://192.168.32.131:8081/
效果
进入Keepalived配置文件目录
cd /etc/keepalived
cp keepalived.conf keepalived.conf.back
修改Keepalived配置文件
vim keepalived.conf
配置文件内容为:
! Configuration File for keepalived
global_defs {
router_id 192.168.32.131
}
vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -20
fall 2
rise 1
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 100
advert_int 1
nopreempt
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.32.200
}
}
大致讲解一下配置文件内容:
增加chk_nginx脚本监测nginx进程
touch check_nginx.sh
vim check_nginx.sh
脚本内容:
#!/bin/bash
A=`ps -C nginx --no-header | wc -l`
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
else
exit 0
fi
else
exit 0
fi
给脚本文件赋予执行权限
chmod 777 check_nginx.sh
启动Keepalived
systemctl start keepalived
验证准备性
网卡是否正确显示虚拟IP(ip addr)
访问虚拟IP地址:http://192.168.32.200:8081/
手动kill掉nginx,看keepalived是否能够自动启动nginx,再次启动则为成功
ps -ef | grep nginx
kill -9 两个nginx进程号
# 等个几秒钟
ps -ef | grep nginx
只有keepalived.conf文件内容不一致外,其他均相同,验证方式也一样
! Configuration File for keepalived
global_defs {
router_id 192.168.32.129
}
vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -20
fall 2
rise 1
}
vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 51
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.32.200
}
}