Reputation: 7394
How can I delete a docker container with force ignore that means if there is no running docker container it should do nothing and if there is a running docker container with the name then it should stop and remove that container.
I am executing the following code to stop and remove the container.
docker rm -f CONTAINER_NAME || true
If there is a running container then everything works fine, however, if there is no container then the following error is thrown:
Error: No such container: CONTAINER_NAME
Is there something like --force ignore
? I need this behaviour in order to include it in an automated Makefile.
Upvotes: 3
Views: 9657
Reputation: 4273
I prefer
docker container inspect CONTAINER_NAME &>/dev/null && docker rm -f CONTAINER_NAME
Solution based on this answer: docker container inspect
sets return-code to 1 if container does not exist, else sets it to 0, so docker rm
will be executed, too.
Upvotes: 0
Reputation: 9240
You can add OR true value, as per below:
One Container
docker rm -f CONTAINER_1 || true
Multiple Containers
(docker rm -f CONTAINER_1 || true) && (docker rm -f CONTAINER_2 || true)
Upvotes: 0
Reputation: 5465
As an alternative you can run container with docker run --rm
. Container will remove itself once stopped.
Upvotes: -1
Reputation: 51
Makefiles have built-in support to ignore errors on a specific command by adding a dash before the command.
rmDocker:
-docker rm -f CONTAINER_NAME
@echo "Container removed!"
You'll still see the error message, but the makefile will ignore the error and proceed anyway.
Output:
docker rm -f CONTAINER_NAME
Error: No such container: CONTAINER_NAME
make: [rmDocker] Error 1 (ignored)
Container removed!
Reference: GNU Make Manual
Upvotes: 1
Reputation: 18598
try this exit code will be 1:
docker rm -f CONTAINER_NAME 2> /dev/null
this with exit code 0:
docker rm -f CONTAINER_NAME 2> /dev/null || true
Upvotes: 7