nginx定时重启及失败重试
nginx定时重启及失败重试
以下是进一步改进的脚本,在停止或重启失败时会进行循环尝试,直到成功或达到最大尝试次数:touch /opt/openresty/log/restart_openresty_with_retry.sh
chmod +x /opt/openresty/log/restart_openresty_with_retry.shcrontab -e
0 2 * * * sh /opt/openresty/log/restart_openresty_with_retry.sh >> /opt/openresty/log/restart_openresty_with_retry.log 2>&1#!/bin/bash
# OpenResty 重启脚本,包含循环尝试逻辑
OPENRESTY_PATH="/opt/openresty" # OpenResty 安装根目录
MAX_ATTEMPTS=5 # 最大尝试次数
ATTEMPT_INTERVAL=3 # 每次尝试的间隔时间(秒)# 停止 OpenResty 函数
stop_nginx() {local attempt=1while [ $attempt -le $MAX_ATTEMPTS ]; doecho "[$(date)] 第 $attempt 次尝试停止 Nginx..."${OPENRESTY_PATH}/nginx/sbin/nginx -s stopsleep $ATTEMPT_INTERVAL# 判断是否停止成功is_stopped=$(ps -ef | grep nginx | grep -v grep | wc -l)if [ $is_stopped -eq 0 ]; thenecho "[$(date)] Nginx 停止成功"return 0elseecho "[$(date)] 第 $attempt 次停止 Nginx 失败,准备强制杀死进程"pkill -9 nginxsleep $ATTEMPT_INTERVAL# 再次检查是否停止成功is_stopped=$(ps -ef | grep nginx | grep -v grep | wc -l)if [ $is_stopped -eq 0 ]; thenecho "[$(date)] 强制杀死 Nginx 进程成功"return 0fifiattempt=$((attempt + 1))doneecho "[$(date)] 达到最大尝试次数,停止 Nginx 失败"return 1
}# 启动 OpenResty 函数
start_nginx() {local attempt=1while [ $attempt -le $MAX_ATTEMPTS ]; doecho "[$(date)] 第 $attempt 次尝试启动 Nginx..."${OPENRESTY_PATH}/nginx/sbin/nginxsleep $ATTEMPT_INTERVAL# 判断是否启动成功is_running=$(ps -ef | grep nginx | grep -v grep | wc -l)if [ $is_running -gt 0 ]; thenecho "[$(date)] Nginx 启动成功"return 0elseecho "[$(date)] 第 $attempt 次启动 Nginx 失败"fiattempt=$((attempt + 1))doneecho "[$(date)] 达到最大尝试次数,启动 Nginx 失败"return 1
}# 执行停止和启动
echo "[$(date)] 开始重启 Nginx 流程"
if stop_nginx; thenecho "[$(date)] 停止 Nginx 阶段完成,开始启动 Nginx"if start_nginx; thenecho "[$(date)] Nginx 重启成功"elseecho "[$(date)] Nginx 重启失败(启动阶段失败)"fi
elseecho "[$(date)] Nginx 重启失败(停止阶段失败)"
fi
代码说明
- 循环停止逻辑:
- 定义 stop_nginx 函数,在函数内通过 while 循环进行最多 MAX_ATTEMPTS 次停止尝试。
- 每次尝试先执行正常停止命令 nginx -s stop ,然后检查是否停止成功。若未成功,执行强制杀死进程命令 pkill -9 nginx ,再次检查是否停止成功。
- 每次尝试间隔 ATTEMPT_INTERVAL 秒。
- 循环启动逻辑:
- 定义 start_nginx 函数,在函数内通过 while 循环进行最多 MAX_ATTEMPTS 次启动尝试。
- 每次尝试执行启动命令 nginx ,然后检查是否启动成功。
- 每次尝试间隔 ATTEMPT_INTERVAL 秒。
- 流程控制:
- 先调用 stop_nginx 函数停止 Nginx,若停止成功,再调用 start_nginx 函数启动 Nginx。
- 根据停止和启动函数的返回值(成功返回 0 ,失败返回 1 ),输出最终的重启结果。
将此脚本保存(比如 ~/restart_openresty_with_retry.sh )并赋予执行权限( chmod +x ~/restart_openresty_with_retry.sh ),然后在 crontab 中配置定时任务( 0 2 * * * /root/restart_openresty_with_retry.sh ),即可实现每天 2 点定时循环尝试重启 Nginx。