Stop and delete docker container if it's running

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.


I have a similar problem, but didn't like the accepted answer as it suppresses all errors from the commands, rather than just the "not found" error.

However, docker ps -q --filter "name=rabbitmq" only produces output if a container of that name actually exists, so inspired by Test if a command outputs an empty string I came up with:

docker ps -q --filter "name=rabbitmq" | grep -q . && docker stop rabbitmq && docker rm -fv rabbitmq

The following command is also useful for testing filter definitions:

docker ps -q --filter "name=rabbitmq" | grep -q . && echo Found || echo Not Found

My actual use case was in defining a pair of Ansible tasks that deleted all currently existing containers (whether running or not) from a list of names generated in an earlier task:

- name: Check for containers that actually exist
  shell: 'docker ps -aq --filter "name={{ item }}"'
  with_items:
    - '{{ previous_command.stdout_lines }}'
  register: found_containers

- name: Remove the containers found by the above command
  shell: 'docker stop {{ item.item }} && docker rm -fv {{ item.item }}'
  with_items: '{{ found_containers.results }}'
  when: item.stdout

Been using docker for a while longer now. This is my preferred way to stop and remove a docker container. The piping of true is there to ensure that it always outputs a success. Without it, any bash scripts would exit and error if the container name did not exist.

docker rm -f container_name || true