Nginx+keepalived
准备两台虚拟机
- 关闭防火墙以及安全系统
- 编译安装nginx
yum -y install gcc pcre-devel openssl-devel zlib-devel openssl openssl-devel
useradd -M -s /sbin/nologin nginx
cd /opt
tar zxvf nginx-1.22.0.tar.gz
cd nginx-1.22.0/
./configure --prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
make && make install
chown -R nginx.nginx /usr/local/nginx
ln -s /usr/local/nginx/sbin/nginx /usr/sbin/
vim /lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/run/nginx.pid
#注意文件位置,如果不对 启动不了
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
#注意启动文件位置
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
[Install]
WantedBy=multi-user.target
mkdir -p /usr/local/nginx/run/
vim /usr/local/nginx/conf/nginx.conf
#找到 pid的位置修改
pid /usr/local/nginx/run/nginx.pid;
systemctl daemon-reload
chown -R nginx.nginx /usr/local/nginx
systemctl start nginx.service
systemctl enable nginx.service
- 安装keepalived
yum -y install keepalived
- 修改keepalived中的配置文件
在/etc/keepalived/keepalived.conf中设置修改两个虚拟机的主从,以及访问的虚拟IP地址以及优先级
用脚本验证服务
- 使用一个脚本,用来监听nginx的状态,如果nginx属于关闭的状态,用脚本将keepalived服务关闭,让backup代替master
A=`ps -C nginx --no-header |wc -l`
if [ $A -eq 0 ];then #如果nginx没有启动就启动nginx
systemctl start nginx #重启nginx
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then #nginx重启失败,则停掉keepalived服务,进行VIP转移
killall keepalived
fi
Fi