1

I use docker container stop xxx. It will cause jenkins fail if docker container xxx is not existed.

I want to know if there is an argument to stop a container without failing.It means when container exists, delete it, otherwise do nothing.

fwhez
  • 561
  • 4
  • 10

3 Answers3

2

You can use the below command :

docker container ps -all --filter "id=XXXXXX" --format {{.ID}} |xargs --no-run-if-empty docker container stop

Explanation :

docker container ps -all: This command will list all the containers.

docker container ps -all --filter "id=XXXXXX": This command will list the container with container id = XXXXXX.

docker container ps -all --filter "id=XXXXXX" --format {{.ID}} : This command will only print out the container id.

We will use this container id to pass it to the xargs command to run the docker container stop.

xargs --no-run-if-empty docker container stop: This command will stop docker container only if command before "|" (pipe) is non-empty.

Pacifist
  • 3,025
  • 2
  • 12
  • 20
2

use this :

docker stop CONTAINER_NAME 2> /dev/null || true

will always give you exit code 0

LinPy
  • 16,987
  • 4
  • 43
  • 57
  • Can you explain it? I can hardly understand it, but it works too. 3Q!!!!!!! – fwhez Sep 18 '19 at 10:15
  • `2>` redirect the output , so you do not see any output from the command , and if it fail `|| true` will set the exit code to `0` – LinPy Sep 18 '19 at 10:21
0

You can manage in a simple way as mentioned below:

docker stop XXXX || true && docker rm XXXX || true

This will return true in either case and it will move out with success.

Reference in details at : stop and delete docker container if its running

Krunal Barot
  • 914
  • 6
  • 17