Remove Exited Containers from Docker
If you use Docker frequently, you’ve probably noticed that stopped or exited containers can pile up and consume a significant amount of disk space over time.
By default, Docker does not automatically delete containers when they stop running.
To remove all exited containers in one simple command, use the following:
docker rm -v $(docker ps -a -q -f status=exited)
How the command works:
docker ps -a -q -f status=exited: This part of the command lists all containers (-a), only outputs their IDs (-q), and filters the list to only include containers with anexitedstatus (-f status=exited).docker rm -v: This takes the list of container IDs generated by the first command and removes them (rm). The-vflag ensures that any associated anonymous volumes are also removed, preventing “dangling” volumes from eating up disk space.
Using Docker Prune (The Modern Way)
In newer versions of Docker (1.13 and up), there is a built-in command specifically designed to clean up your environment:
docker container prune
This command will prompt you for confirmation and then remove all stopped containers. If you want to bypass the confirmation prompt (for example, in a script), you can add the -f or --force flag:
docker container prune -f
To clean up everything at once (stopped containers, unused networks, dangling images, and build cache), you can use the system-wide prune command:
docker system prune