使用Docker容器部署镜像,可能需要定时检查磁盘空间。
- 编写 shell 脚本 threshold_script.sh
#!/bin/bash
LOG_FILE="/home/sh/threshold_script.log"
# 定义记录日志的函数
log() {
local timestamp=$(date "+%Y-%m-%d %H:%M:%S")
local log_message="[$timestamp] $1"
echo "$log_message" >> "$LOG_FILE"
echo "$log_message"
}
disk_space=$(df -h / | awk 'NR==2 {print $4}' | sed 's/G//')
threshold=50
if [ "$disk_space" -lt "$threshold" ]; then
log "磁盘剩余空间${disk_space}G,小于 ${threshold}G,执行 docker system prune ..."
docker system prune -f
log "docker system prune 完成。"
else
log "磁盘剩余空间${disk_space}G,大于等于 ${threshold}G,无需执行 docker system prune。"
fi
- 配置到系统定时任务中
crontab -e
0 * * * * /bin/bash /home/sh/threshold_script.sh
- 重启定时任务
systemctl restart cron # Ubuntu
systemctl restart crond # Centos