如果系统负载过大,可以自动重启nginx,短暂的释放负载。
设置步骤如下
步骤#01: 宝塔后台添加脚本
脚本可以设置为5分钟检查一下

脚本内容如下:
#!/bin/bash
# 获取CPU核心数
cpu_cores=$(nproc)
echo "Current CPU cores: $cpu_cores"
# 计算阈值(核心数 * 0.7)
threshold=$(echo "$cpu_cores * 0.7" | bc)
echo "Load threshold: $threshold"
# 获取1分钟平均负载
load_average=$(uptime | awk -F'[, ]+' '{ print $12 }')
echo "Current 1-minute load average: $load_average"
# 检查负载是否大于阈值
if (( $(echo "$load_average > $threshold" | bc -l) )); then
echo "High load detected, attempting to restart Nginx."
# 使用指定的命令重启Nginx服务
/etc/init.d/nginx restart
# 短暂等待
sleep 5
# 检查Nginx是否成功启动
if ! pgrep nginx > /dev/null 2>&1; then
echo "Nginx did not start successfully. Attempting to restart again."
# 如果Nginx没有成功启动,尝试再次启动
/etc/init.d/nginx restart
fi
else
echo "Load is below threshold. No action taken."
fi
步骤#02: 检查脚本是否正常
脚本添加以后,点击“执行”,看一下脚本的Log是否正常
没有执行重启Nginx的Log:

重启Nginx的Log:
这里重启了Nginx是因为我更改了threshold为0.3,所以自动重启了Nginx,正常情况下threshold是4.2,是不会重启了,为了测试,将其改为了0.3.

注意:
注意Log中会有一句“Current 1-minute load average: 0.41“ ,如果0.41这个位置不是一个数字,而是一个单词,说明这个脚本是有问题的,需要修复。
遇到的问题:
问题01: bc command not found
解决方法:
使用以下命令安装 bc
:

Leave a Reply