Docker

Stop and remove all docker containers with easy commands !

STOP REMOVE ALL DOCKER CONTAINERS

If you are looking for how to stop and remove all running docker containers, here are a few simple commands to help. These are valid for docker compose also.

Docker commands are not OS specific so these should run fine on Ubuntu, Windows, or Mac.

There are multiple ways to achieve it. This blog post will list down many of them. Feel free to use whichever you seem to like.

Since we cannot remove a running docker image, we ill first stop all of them with a command, then delete images.

1. Stop all dockers

docker stop $(docker ps -a -q)

2. Remove all dockers

Once all the dockers are stopped, remove all docker containers by running the following command :

docker rm $(docker ps -a -q)

3. Delete docker all images

docker rmi $(docker ps -a -q)

4. Remove all mounted volumes

 docker volume ls -qf dangling=true | xargs -r docker volume rm

5. Remove specific docker images

Herein we will be using the example on how to remove all the Redis instances only.

 docker rm (docker ps -a |grep redis |awk '{print $1}')

[su_label type=”success”]Suggested read : [/su_label] Forever free blog with Google App Engine WordPress in 10 min

Few more helpful commands :

  • Remove all containers forcefully docker rm -f $(docker ps -a -q)
  • Remove all docker images forcefully docker rmi -f $(docker images -q)
  • Purge remaining things : docker system prune --all --force --volumes
  • To only stop exited containers and delete only non-tagged images :
    docker ps --filter 'status=Exited' -a | xargs docker stop docker images --filter "dangling=true" -q | xargs docker rmi
  • Create a bash or shell alias and use it frequently : dstop() { docker stop $(docker ps -a -q); } alias dstop=dstop

Basic docker commands that might help :

  • List all docker images : sudo docker ps
  • Stop single running docker container : sudo docker stop 9ab3de2442e2
  • Display container IDs of docker : sudo docker ps -aq
  • Clean docker stuff :  sudo docker system prune

Here’s a one-liner script to do all of these tasks :

docker ps | awk {' print $1 '} | tail -n+2 > tmp.txt; for line in $(cat tmp.txt); do docker kill $line; done; rm tmp.txt

[su_label type=”success”]Suggested read : [/su_label] How to install docker on ubuntu

I found an awesome script that also does a similar work of cleaning and removing all docker containers but more cleanly :

Let us know if you faced any issue or have better commands to share to stop or docker remove all containers, in the comments below.

Related posts:

Exec Format Error in Docker
Docker

Exec Format Error in Docker: Causes and Solutions

This post fixes Exec Format Error in Docker. Docker is an essential tool for developers, simplifying the process of managing