停止并删除docker容器如果它的运行 [英] stop and delete docker container if its running

查看:3646
本文介绍了停止并删除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 im looking to do

docker stop rabbitmq && docker rm -f rabbitmq

然而,它将它整理成一个我想知道的脚本?它会看起来像这样。

However its 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


推荐答案

您可能已经注意到,如果容器不是,$ code> 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命令失败: p>

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容器如果它的运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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