温馨提示×

怎样自动linux cleanup

小樊
41
2026-09-14 13:27:26
栏目: 智能运维

在 Linux 系统上做“自动 cleanup(自动清理)”通常有几种常见场景和做法。下面按使用频率从高到低给你一个实用指南。


一、用 cron 定时自动清理(最常用)

1. 清理临时文件

# 每天凌晨 3 点清理 /tmp 中 7 天前的文件
0 3 * * * find /tmp -type f -mtime +7 -delete

2. 清理日志文件

# 每周清理 /var/log 下超过 30 天的 .log
0 4 * * 0 find /var/log -name "*.log" -mtime +30 -delete

3. 清理用户缓存

0 2 * * * find ~/.cache -type f -mtime +14 -delete

编辑定时任务:crontab -e


二、使用系统自带工具(推荐)

1. systemd-tmpfiles(现代 Linux 推荐)

配置文件在:

/etc/tmpfiles.d/

示例(清理 /tmp 中 10 天前的文件):

# /etc/tmpfiles.d/cleanup.conf
d /tmp 1777 root root 10d

手动执行:

systemd-tmpfiles --clean

三、自动清理 Docker(常见痛点)

# 每天清理无用容器、镜像、卷
0 1 * * * docker system prune -af

更安全的:

docker image prune -af --filter "until=72h"

四、自动清理 apt / yum 缓存

Debian / Ubuntu

apt-get clean
apt-get autoremove -y

CentOS / RHEL

yum clean all

可写入 cron:

0 5 * * 0 apt-get clean && apt-get autoremove -y

五、日志自动轮转(logrotate)

系统已默认启用:

/etc/logrotate.conf
/etc/logrotate.d/

示例:

/var/log/myapp.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
}

六、进阶:写 cleanup 脚本

#!/bin/bash
# /usr/local/bin/cleanup.sh

find /tmp -mtime +7 -delete
docker system prune -af
apt-get clean
chmod +x /usr/local/bin/cleanup.sh

cron:

0 3 * * * /usr/local/bin/cleanup.sh

七、注意事项(很重要)

  • ❌ 不要随意 rm -rf /
  • ✅ 先用 find ... -print 测试
  • ✅ 重要数据做好备份
  • ✅ 生产环境避免 prune -a

如果你能告诉我:

  • 服务器 / 桌面 / Docker / CI
  • 想清理 日志 / 容器 / 缓存 / 磁盘

我可以给你一套精准的自动清理方案

0