I cannot tell you how many times I’ve had way too many Docker containers running and wanted to just blow them all away and start over. Granted, I wouldn’t do this on a production machine; but if you’re working on a development environment where it doesn’t matter if you kill every running container, then using this nuclear option is a good way to go.
For instance, you might need to deploy a new testing container on a port that some other test container is using. Instead of tracking that container down – and as long as you don’t need any other container to stay running – there’s a much easier solution for this. What I’m about to show you does exactly what it sounds like.
The first command will stop all running containers, and the second command deletes them. It works every time. Here’s how you do it.
To stop all of your running Docker containers, issue the command docker stop $(docker ps -a -q). The next command removes all containers, which is docker remove $(docker ps -a -q).
As you can see, there are two commands: docker remove (or stop) and docker ps -a -q. The first command uses the output of the second command as a variable, so if you have multiple containers running, it’ll either stop or remove them all at once. This command comes in very handy, though remember to use it wisely. If you have any containers running that must remain up, you’re better off stopping and removing the containers manually.
Subscribe to TechRepublic’s How To Make Tech Work on YouTube for all the latest tech advice for business pros from Jack Wallen.
If you are interested in learning more about Docker, check out the following resources in TechRepublic Academy:
The 2023FullStack Developer Bundle
Hacking and Securing Docker Containers
Linux and Docker Coding Bundle
Docker and Kubernetes mini-bundle