Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

bash - Docker: Stop and delete docker container if it's running

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...