如何每天自动删除未关联到容器的 docker 镜像
注意:这不仅会删除没有标签的 docker 镜像,还会删除所有未关联到运行中或已停止容器的 docker 镜像。如果这不是期望的行为,请参见我们之前的文章如何每天自动清理(修剪)docker 镜像。
docker image prune 提供了一种简单的方法从系统中删除"未使用的" docker 镜像,从而修复或显著延迟 docker 占用所有磁盘空间的问题。
我使用 TechOverflow 的 简单 systemd 定时器生成器 创建了基于 systemd 定时器的每日镜像删除例程。
快速安装使用
install-cleanup-docker-all.sh
wget -qO- https://techoverflow.net/scripts/install-cleanup-docker-all.sh | sudo bash这是自动创建并安装两个 systemd 配置文件的脚本。
install-prune-docker-all.sh
#!/bin/sh
# 此脚本安装自动 docker 清理。
# 到基于 systemd 的系统上。
# 参见 https://techoverflow.net/2020/02/04/how-to-remove-all-docker-images-that-are-not-associated-to-a-container/
# 了解删除哪些镜像的详细信息。
# 它要求 docker 已正确安装
cat >/etc/systemd/system/PruneDockerAll.service <<EOF
[Unit]
Description=PruneDockerAll
[Service]
Type=oneshot
ExecStart=/bin/bash -c "docker image ls --format '{{.ID}}' | xargs docker image rm ; true"
WorkingDirectory=/tmp
EOF
cat >/etc/systemd/system/PruneDockerAll.timer <<EOF
[Unit]
Description=PruneDockerAll
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
EOF
# 启用并启动服务
systemctl enable PruneDockerAll.timer && sudo systemctl start PruneDockerAll.timer要查看日志,使用
prune-docker-logs.sh
journalctl -xfu PruneDockerAll.service要查看状态,使用
prune-docker-status.sh
sudo systemctl status PruneDockerAll.timer要立即清理你的 docker 镜像,使用
prune-docker-now.sh
sudo systemctl start PruneDockerAll.serviceCheck out similar posts by category:
Docker
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow