在 CentOS 上实现 自动清理(cleanup),通常从 日志、YUM/DNF 缓存、临时文件、旧内核、Docker 等方面入手。下面给你一套 可自动化、可生产使用 的方案。
| 类型 | 内容 |
|---|---|
| 日志 | /var/log |
| 包管理器缓存 | yum / dnf cache |
| 临时文件 | /tmp、/var/tmp |
| 旧内核 | 防止 /boot 满 |
| Docker | 镜像 / 容器 / 卷 |
| 自定义目录 | 日志、缓存、备份 |
sudo vi /usr/local/bin/centos-cleanup.sh
#!/bin/bash
# centos-cleanup.sh
echo "=== Clean YUM/DNF cache ==="
yum clean all
dnf clean all 2>/dev/null
echo "=== Remove old kernels (keep 2) ==="
if command -v package-cleanup &>/dev/null; then
package-cleanup --oldkernels --count=2 -y
fi
echo "=== Clean /tmp & /var/tmp ==="
find /tmp -type f -atime +7 -delete
find /var/tmp -type f -atime +7 -delete
echo "=== Clean journal logs (keep 7 days) ==="
journalctl --vacuum-time=7d
echo "=== Clean log files > 100M ==="
find /var/log -type f -name "*.log" -size +100M -exec truncate -s 0 {} \;
echo "=== Done ==="
sudo chmod +x /usr/local/bin/centos-cleanup.sh
sudo vi /etc/systemd/system/centos-cleanup.service
[Unit]
Description=CentOS Cleanup Service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/centos-cleanup.sh
sudo vi /etc/systemd/system/centos-cleanup.timer
[Unit]
Description=Run CentOS cleanup daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable centos-cleanup.timer
sudo systemctl start centos-cleanup.timer
查看状态:
systemctl list-timers centos-cleanup.timer
✅ 这是最推荐的方式(比 cron 更稳定)
sudo crontab -e
0 2 * * * /usr/local/bin/centos-cleanup.sh >> /var/log/centos-cleanup.log 2>&1
docker system prune -af --volumes
docker system prune -af --volumes
加入 systemd 或 cron 即可。
df -h
du -sh /* | sort -h
可配合 Prometheus / Zabbix / 脚本报警
✅ 只清理 7 天以上 文件
✅ 保留 2 个内核
✅ 日志用 truncate 而不是 rm
✅ 清理前先测试脚本
✅ 做好备份策略
如果你愿意,我可以帮你:
只要告诉我你的 CentOS 版本 + 使用场景 即可。