Created
February 23, 2025 17:39
-
-
Save fabiobarboza7/5c1442e0ed0faacd0ebd382249d61923 to your computer and use it in GitHub Desktop.
Docker Full Cleanup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# A Personal Docker Cleanup Script made some years ago by me and now a little bit refined by LLM. | |
# This script will remove all Docker containers, images, volumes, networks, and builders. | |
# You can create an alias for this script in your .bashrc or .zshrc file. I did. | |
# Define style variables | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
YELLOW='\033[1;33m' | |
BLUE='\033[0;34m' | |
NC='\033[0m' # No Color | |
echo -e "${BLUE}This script will remove all Docker containers, images, volumes, networks, and builder cache.${NC}" | |
read -p "Do you want to continue? (y/n) " response | |
if [ "$response" != "y" ]; then | |
echo -e "${YELLOW}Exiting script.${NC}" | |
exit 0 | |
fi | |
# Ensure Docker binary path is available | |
export PATH=$PATH:/usr/local/bin | |
# Stop all running containers | |
running=$(docker container ls -q) | |
if [ -n "$running" ]; then | |
docker container stop $running | |
else | |
echo -e "${RED}No running containers to stop.${NC}" | |
fi | |
# Remove all containers | |
containers=$(docker container ls -aq) | |
if [ -n "$containers" ]; then | |
docker container rm -f $containers | |
else | |
echo -e "${RED}No containers to remove.${NC}" | |
fi | |
# Remove all images | |
images=$(docker image ls -aq) | |
if [ -n "$images" ]; then | |
docker image rm -f $images | |
else | |
echo -e "${RED}No images to remove.${NC}" | |
fi | |
# Remove all volumes | |
volumes=$(docker volume ls -q) | |
if [ -n "$volumes" ]; then | |
docker volume rm -f $volumes | |
else | |
echo -e "${RED}No volumes to remove.${NC}" | |
fi | |
# Remove all networks except the predefined ones (bridge, host, none) | |
networks=$(docker network ls --format '{{.Name}}') | |
for network in $networks; do | |
if [ "$network" != "bridge" ] && [ "$network" != "host" ] && [ "$network" != "none" ]; then | |
docker network rm "$network" | |
else | |
echo -e "${YELLOW}Skipping predefined network: $network${NC}" | |
fi | |
done | |
# Prune the system (unused containers, networks, dangling images, build cache, and volumes) | |
docker system prune -a -f --volumes | |
# Prune builder cache explicitly | |
docker builder prune -a -f | |
# Leave swarm mode if applicable | |
docker swarm leave --force 2>/dev/null | |
echo -e "${GREEN}Docker environment has been completely cleaned.${NC}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment