Deleting all stopped containers and unused networks in Docker is a common cleanup operation that helps maintain the tidiness of the Docker environment and effectively manage resource utilization. To perform these operations, Docker's command-line tools can be used.
First, to delete all stopped containers, use the docker container prune command. This command removes all containers in a stopped state. Before executing this command, you can use the docker ps -a command to view the status of all containers and confirm which ones are stopped. As shown below:
bash# View the status of all containers docker ps -a # Delete all stopped containers docker container prune
When prompted for confirmation, enter 'y' to confirm the deletion. This will clear all stopped containers.
Next, for unused networks, Docker provides the docker network prune command to remove all networks not used by any container. Before executing this command, use the docker network ls command to view existing networks, which helps identify which networks may be unused. As shown below:
bash# View all networks docker network ls # Delete all unused networks docker network prune
Similarly, when prompted for confirmation, enter 'y' to confirm the deletion. This will clear all unused network resources.
By following these steps, you can effectively manage your Docker environment, ensuring that no unnecessary resources consume space. This not only improves system efficiency but also helps avoid issues caused by resource constraints. In practical work, such maintenance operations are essential, especially in environments with frequent resource usage.