You have to take into account at least two cases - removing stopped container, which can be removed with a single command and removing running containers, where the container has to be stopped first before being deleted.
In addition to this, in stead of using
grep to find the container name, I would use the
filter option of
docker ps, that way you won't end up grepping the wrong container just because say the command option matches the name you placed in grep. Here is how I would remove any similar docker containers, strictly follow the below sequence -
- Remove running containers
for container_id in $(docker ps --filter="name=$name" -q);do docker stop $container_id && docker rm $container_id;done
- Remove stopped containers, since we have stopped running containers in step 1.
for container_id in $(docker ps --filter="name=$name" -q -a);do docker rm $container_id;done
-a option will include all containers, including the stopped ones. Not using
-a, the default option, will include only running containers. So on step one, you remove the running containers, and then on step two you proceed with the stopped ones. To remove or stop a container, all you need is the container id, the
-q options outputs only the ID.