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

查看:1756
本文介绍了停止并删除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

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


推荐答案

As您可能已经注意到, 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容器(如果正在运行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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