3

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.

Rene B.
  • 6,557
  • 7
  • 46
  • 72

5 Answers5

6

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
LinPy
  • 16,987
  • 4
  • 43
  • 57
1

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

Etchy
  • 51
  • 4
0

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)

Jerry Chong
  • 7,954
  • 4
  • 45
  • 40
0

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.

not2savvy
  • 2,902
  • 3
  • 22
  • 37
-1

As an alternative you can run container with docker run --rm. Container will remove itself once stopped.

igor
  • 5,351
  • 2
  • 26
  • 22