Docker:停止并删除 docker 容器(如果它正在运行) [英] Docker: Stop and delete docker container if it's running

查看:34
本文介绍了Docker:停止并删除 docker 容器(如果它正在运行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 docker 容器正在运行,我希望务实地停止并删除它.这是一个构建脚本.

I am looking to pragmatically stop and delete a docker container if it is running. This is for a build script.

举个例子.我将如何停止和删除 docker 容器rabbitmq"?如 bash 脚本中的 NAMES 列下所示?

Take the following example. How would I stop and delete the docker container "rabbitmq" as seen under the NAMES column in a bash script?

docker ps

CONTAINER ID        IMAGE             COMMAND                  CREATED             STATUS              PORTS                   NAMES
9909a5e2856f        rabbitmq-image   "/docker-entrypoint.s"   11 minutes ago      Up 11 minutes       0.0.0.0:5672->5672/tcp, rabbitmq
8990dd1fe503        redis-image      "/entrypoint.sh redis"   6 weeks ago         Up 4 days           0.0.0.0:32770->6379/tcp redis
etc 

以下命令将删除容器并执行我想要做的事情

The following command will delete the container and does what I'm looking to do

docker stop rabbitmq && docker rm -f rabbitmq

但是,它把它组合成一个我想知道的脚本?我认为它看起来像这样.

However, it's combing it into a script that I would like to know? I think it would look something like this.

#!/bin/bash

if [ /*docker ps check some value */ ]; then
   docker stop rabbitmq && docker rm -f rabbitmq
fi

推荐答案

您可能已经注意到,docker stop 以及 docker rm 退出时会显示一个状态码如果容器不存在或未运行,则失败.这会导致您的构建失败.

As you have probably noticed, docker stop as well as docker rm exit with a status code indicating failure if the container is not existent or not running. This results in your build failing.

如果您可以处理构建日志中的错误消息,您可以使用这个小技巧来防止 shell 命令失败:

If you can cope with the error messages in your build log you can do this little trick to prevent the shell command of failing:

docker stop rabbitmq || true && docker rm rabbitmq || true

如果 docker 命令中的一个失败,true 会被调用,它总是退出并显示成功的状态码.

In the case that one of the docker command fails, true is called which always exits with a status code indicating success.

这篇关于Docker:停止并删除 docker 容器(如果它正在运行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆