How to remove old Docker containers?

Docker allows you to remove old and stale containers that are no longer needed. You can use the docker rm or docker container rm commands to accomplish this. However, before removing containers, ensure that none are actively running, as Docker will throw an error for running containers.

There is a workaround for this − you can remove Docker containers forcefully using the --force option. The Docker remove commands allow you to remove one or more containers together by specifying their container IDs or names. If you want to delete all Docker containers simultaneously, you can achieve this using sub-commands.

Docker Container Remove Commands

You can use two different forms of the Docker container remove command to achieve the same result −

$ docker container rm [OPTIONS] CONTAINER [CONTAINER...]
$ docker rm [OPTIONS] CONTAINER [CONTAINER...]

Both commands work identically. The available options are −

  • --volumes − Remove associated volumes along with the container
  • --link − Remove links between containers
  • --force − Forcefully remove running containers without stopping them first

Examples

Removing a Single Container

To remove a container called mycont, first check if it's running −

$ docker ps

If the container is active, stop it first −

$ docker stop mycont

Then remove the container −

$ docker container rm mycont

Or using the shorter form −

$ docker rm mycont

Force Removal

To avoid the stop-then-remove process, use the force option −

$ docker rm -f mycont

This removes the container even if it's actively running.

Removing Multiple Containers

Remove multiple containers by specifying their names or IDs −

$ docker container rm mycont1 mycont2 mycont3

Removing All Containers

To remove all containers, first stop them −

$ docker stop $(docker ps -aq)

Then remove all stopped containers −

$ docker rm $(docker ps -aq)

The -q (quiet) option returns only container IDs, while -a (all) includes all containers regardless of status.

For force removal of all containers −

$ docker rm -f $(docker ps -aq)

Removing Only Stopped Containers

To remove only containers with "exited" status −

$ docker rm $(docker ps --filter status=exited -q)

Key Points

  • Always check container status before removal
  • Use --force to remove running containers without stopping
  • Sub-commands with $(docker ps -aq) help manage multiple containers
  • Filters allow selective removal based on container status

Conclusion

Docker provides flexible options for removing containers using docker rm and docker container rm commands. You can remove single containers, multiple containers, or all containers at once using various options and sub-commands for efficient container management.

Updated on: 2026-03-17T09:01:38+05:30

766 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements