这个问题与我是否应该关注过量的、未运行的Docker容器有关。
我想知道如何移除旧容器。docker rm 3e552code34a允许你删除一个,但我已经有很多了。Docker rm——help没有提供选择选项(像all一样,或者通过映像名称)。
也许有一个存放这些容器的目录,我可以很容易地手动删除它们?
这个问题与我是否应该关注过量的、未运行的Docker容器有关。
我想知道如何移除旧容器。docker rm 3e552code34a允许你删除一个,但我已经有很多了。Docker rm——help没有提供选择选项(像all一样,或者通过映像名称)。
也许有一个存放这些容器的目录,我可以很容易地手动删除它们?
当前回答
下面是我的docker-cleanup脚本,它删除未标记的容器和图像。请检查来源的任何更新。
#!/bin/sh
# Cleanup docker files: untagged containers and images.
#
# Use `docker-cleanup -n` for a dry run to see what would be deleted.
untagged_containers() {
# Print containers using untagged images: $1 is used with awk's print: 0=line, 1=column 1.
docker ps -a | awk '$2 ~ "[0-9a-f]{12}" {print $'$1'}'
}
untagged_images() {
# Print untagged images: $1 is used with awk's print: 0=line, 3=column 3.
# NOTE: intermediate images (via -a) seem to only cause
# "Error: Conflict, foobarid wasn't deleted" messages.
# Might be useful sometimes when Docker messed things up?!
# docker images -a | awk '$1 == "<none>" {print $'$1'}'
docker images | tail -n +2 | awk '$1 == "<none>" {print $'$1'}'
}
# Dry-run.
if [ "$1" = "-n" ]; then
echo "=== Containers with uncommitted images: ==="
untagged_containers 0
echo
echo "=== Uncommitted images: ==="
untagged_images 0
exit
fi
# Remove containers with untagged images.
echo "Removing containers:" >&2
untagged_containers 1 | xargs --no-run-if-empty docker rm --volumes=true
# Remove untagged images
echo "Removing images:" >&2
untagged_images 3 | xargs --no-run-if-empty docker rmi
来源:https://github.com/blueyed/dotfiles/blob/master/usr/bin/docker-cleanup
其他回答
官方的说法是:
docker rm `docker ps -aq`
Docker的维护者已经表示不会有这样的命令——你可以像这样组合命令:
我们之前讨论过这个问题,希望用户使用上面的代码行,而不必向Docker添加额外的代码。
对于感兴趣的人,我从qkrijger中取了一个例子,并将其转换为clear all(停止并删除所有)
docker stop `docker ps --no-trunc -aq` ; docker rm `docker ps --no-trunc -aq`
你可以停止docker容器,一旦停止,你可以删除容器。
停止容器:
$ docker stop "containerID" -你也可以提到容器ID的前两个字母,它是有效的。
取出容器
$ docker rm "containerID" -同样你也可以提到容器的前两个字母
如果这些命令不让你停止/删除容器,m,确保你有sudo访问docker主机。
对于Linux安装,请确保使用sudo。另外,寻找几个月或几周前的图像也很好:
sudo docker ps -a | grep 'weeks ago\|months ago' | \
awk '{print $1}' | xargs --no-run-if-empty sudo docker rm
一个伟大的自动替代- containrrr/watchtower
它包含图像自动清理,更新和监控选项
version: "3.9"
services:
service:
container_name: watchtower
image: containrrr/watchtower:latest
hostname: watchtower
environment:
- TZ=Europe/Bucharest
- WATCHTOWER_CLEANUP=true
- WATCHTOWER_INCLUDE_RESTARTING=true
- WATCHTOWER_POLL_INTERVAL=86400
#- WATCHTOWER_SCHEDULE=0 0 4 * * *
- WATCHTOWER_LABEL_ENABLE=false
- WATCHTOWER_MONITOR_ONLY=false
- WATCHTOWER_NO_PULL=false
- WATCHTOWER_NO_RESTART=false
volumes:
- /var/run/docker.sock:/var/run/docker.sock
restart: unless-stopped