bash 按图像名称停止 docker 容器,如果没有容器正在运行,则不要出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37182148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stopping docker containers by image name, and don't error if no containers are running
提问by Richard
This questionexplains how to stop Docker containers started from an image.
这个问题解释了如何停止从镜像启动的 Docker 容器。
But if there are no running containers I get the error docker stop requires a minimum of one argument. Which means I can't run this command in a long .sh script without it breaking.
但是如果没有正在运行的容器,我会收到错误docker stop requires a minimum of one argument。这意味着我无法在不中断的情况下在长 .sh 脚本中运行此命令。
How do I change these commands to work even if no results are found?
即使未找到结果,如何更改这些命令以使其正常工作?
docker stop $(docker ps -q --filter ancestor="imagname")
docker rm `docker ps -aq` &&
(I'm looking for a pure Docker answer if possible, not a bash test, as I'm running my script over ssh so I don't think I have access to normal script tests)
(如果可能的话,我正在寻找一个纯粹的 Docker 答案,而不是 bash 测试,因为我正在通过 ssh 运行我的脚本,所以我认为我无法访问正常的脚本测试)
回答by Farhad Farahi
Putting this in case we can help others:
把这个放在我们可以帮助别人的情况下:
To stop containers using specific image:
要停止使用特定图像的容器:
docker ps -q --filter ancestor="imagename" | xargs -r docker stop
To remove exited containers:
要删除退出的容器:
docker rm -v $(docker ps -a -q -f status=exited)
To remove unused images:
要删除未使用的图像:
docker rmi $(docker images -f "dangling=true" -q)
If you are using a Docker > 1.9:
如果您使用的是 Docker > 1.9:
docker volume rm $(docker volume ls -qf dangling=true)
If you are using Docker <= 1.9, use this instead:
如果您使用的是 Docker <= 1.9,请改用:
docker run -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/docker:/var/lib/docker --rm martin/docker-cleanup-volumes
Docker 1.13 Update:
Docker 1.13 更新:
To remove unused images:
要删除未使用的图像:
docker image prune
To remove unused containers:
要删除未使用的容器:
docker container prune
To remove unused volumes:
要删除未使用的卷:
docker volume prune
To remove unused networks:
删除未使用的网络:
docker network prune
To remove all unused components:
要删除所有未使用的组件:
docker system prune
IMPORTANT: Make sure you understand the commands and backup important data before executing this in production.
重要提示:在生产中执行此操作之前,请确保您了解命令并备份重要数据。