Docker commands to stop and remove all images and containers

Anup Kumar
3 min readOct 22, 2019

--

It’s useful to clean all or specific Docker images and containers. Below are some handy commands to clean up,

Containers commands

The below are docker container-related commands,

List all containers (only IDs)

docker ps -aq

List all containers

docker container ps

List all active containers

docker container ls -a

To get a list of all active and inactive containers, pass the -a flag to the docker container ls command:

The output will look something like this:

Stop all running containers

docker stop $(docker ps -aq)

Stop a particular container

docker container stop <<container_id>>

Start a container

docker container start <<container_id>>

Remove all containers

docker rm $(docker ps -aq)

Remove a particular container

Once you know the CONTAINER ID you want to delete, pass it to the docker container rm command.

docker container rm <<container_id>>

To force delete it add -f before the container id

If you get an error similar to the below, it means that the specified container is running and need to stop the container before removing it.

Error response from daemon: You cannot remove a running container <<container id>>. Stop the container before attempting removal or force remove.

Remove multiple containers

Once you know the CONTAINER ID's you want to delete, pass it to the docker container rm command.

docker container rm <<container_id_1>> <<container_id_2>>

To force delete it add -f before the container id

If you get an error similar to the below, it means that the specified container is running and need to stop the container before removing it.

Error response from daemon: You cannot remove a running container <<container id>>. Stop the container before attempting removal or force remove.

Image Commands

The below are docker image-related commands,

List all images

docker image ls

Remove all images

docker rmi $(docker images -q)

Remove all unused images

To remove all images which are not referenced by any existing container, use the prune command with the -a flag:

docker image prune -a

Remove a particular image

Once you know the IMAGE ID you want to delete, pass it to the docker image rmi command.

docker image rmi <<image_id>>

To force delete it add -f before the image id.

If any error is thrown stating that there are active dependent containers or images, one needs to delete them before removing the image

Conclusion

In this guide, you see some of the common commands for removing Docker containers, images.

You should also check out the official Docker documentation.

Please leave a comment below if you have any questions.

--

--

Anup Kumar

CTO @Urbanetic | Founder @oclavi | Former Architect @KAPSARC — Data Science, AI & ML enthusiast