Ubuntu 20.04服务器网站502时自动重启Nginx的脚本编写及手动重启方法
一、手动重启Ubuntu 20.04上的Nginx守护进程
Ubuntu 20.04基于systemd管理服务,常用的Nginx重启命令如下:
- 直接重启(先停止再启动):
sudo systemctl restart nginx - 平滑重启(不中断现有客户端连接,适合业务低峰期):
sudo systemctl reload nginx - 若遇到systemctl无法使用的特殊情况,可尝试传统命令:
sudo service nginx restart
重启后可通过以下命令验证状态:sudo systemctl status nginx
二、仅当网站返回HTTP 502时自动重启Nginx的脚本
2.1 Shell脚本实现(轻量推荐)
Shell脚本无需额外依赖,适合服务器环境:
#!/bin/bash # 替换为你的网站实际URL TARGET_URL="http://your-domain.com" # 静默获取HTTP状态码 HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$TARGET_URL") # 判断状态码是否为502 if [ "$HTTP_STATUS" -eq 502 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S'): 检测到502错误,开始重启Nginx..." sudo systemctl restart nginx # 可选:重启后延迟10秒再次检查状态 sleep 10 NEW_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$TARGET_URL") echo "$(date '+%Y-%m-%d %H:%M:%S'): Nginx重启完成,当前状态码为 $NEW_STATUS" fi
使用步骤:
- 将脚本保存为
nginx_auto_restart.sh - 赋予执行权限:
chmod +x nginx_auto_restart.sh - 设置定时任务(每5分钟执行一次):
编辑crontab:crontab -e
添加一行:*/5 * * * * /home/your-user/nginx_auto_restart.sh >> /var/log/nginx_auto_restart.log 2>&1
(替换脚本路径和日志路径为实际路径)
2.2 Python脚本实现
如果习惯用Python,可使用requests库实现:
import requests import subprocess from datetime import datetime import time # 替换为你的网站实际URL TARGET_URL = "http://your-domain.com" try: # 发送请求,超时时间10秒 response = requests.get(TARGET_URL, timeout=10) if response.status_code == 502: current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"{current_time}: 检测到502错误,执行Nginx重启...") # 执行重启命令,需确保脚本执行用户有sudo权限 subprocess.run(["sudo", "systemctl", "restart", "nginx"], check=True) # 重启后再次检查 time.sleep(10) new_response = requests.get(TARGET_URL, timeout=10) print(f"{current_time}: Nginx重启完成,当前状态码为 {new_response.status_code}") except requests.exceptions.RequestException as e: print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: 请求网站失败,错误信息: {str(e)}") except subprocess.CalledProcessError as e: print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}: 重启Nginx失败,错误信息: {str(e)}")
使用步骤:
- 安装依赖库:
pip install requests - 将脚本保存为
nginx_auto_restart.py - 赋予执行权限:
chmod +x nginx_auto_restart.py - 设置定时任务(每5分钟执行一次):
编辑crontab:crontab -e
添加一行:*/5 * * * * /usr/bin/python3 /home/your-user/nginx_auto_restart.py >> /var/log/nginx_auto_restart_py.log 2>&1
(替换Python路径、脚本路径和日志路径为实际路径)
内容的提问来源于stack exchange,提问作者sambit
相关产品推荐
相关产品推荐

