Skip to content

Instantly share code, notes, and snippets.

@MaxenceG2M
Last active March 9, 2023 03:07
Show Gist options
  • Save MaxenceG2M/2c0cc28b9a2bb8be6569 to your computer and use it in GitHub Desktop.
Save MaxenceG2M/2c0cc28b9a2bb8be6569 to your computer and use it in GitHub Desktop.
Bash script to clean docker: stop all containers, rm all container, rmi dangling images
#!/bin/bash
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Usage method
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
usage() {
echo "
Usage : $0 [options]
Clean old docker containers, volumes, etc.
-v : clean volumes (default: disable)
-h : show this help
"
exit 0;
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# check options
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Execute getopt
ARGS=$(getopt -o vh -n "$0" -- "$@");
#~ Bad arguments
#if [ $? -ne 0 ];then
# error
#fi
eval set -- "$ARGS";
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# usage ( validation via getopt )
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
while true ; do
case "$1" in
-h|--help) usage ; shift ;;
-v) VOLUMES=true; shift; ;;
--) shift ; break ;;
*) error ; break ;;
esac
done
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
DONE="[${GREEN}DONE${NC}]"
PROGRESS="[${YELLOW}....${NC}]"
echo -ne "${PROGRESS} Stop all running containers\r"
docker stop $(docker ps -q) 2>/dev/null
echo -ne "${DONE} Stop all running containers\r"
echo -ne '\n'
echo -ne "${PROGRESS} Remove old containers\r"
docker rm $(docker ps -a -q) 2>/dev/null
echo -ne "${DONE} Remove old containers\r"
echo -ne '\n'
echo -ne "${PROGRESS} Remove dangling images\r"
docker rmi $(docker images --filter dangling=true -q) 2>/dev/null
echo -ne "${DONE} Remove dangling images\r"
echo -ne '\n'
if [[ $VOLUMES ]]; then
echo -ne "${PROGRESS} Cleaning volumes\r"
docker volume rm $(docker volume ls -q) 2>/dev/null
echo -ne "${DONE} Cleaning volumes\r"
echo -ne "\n"
fi
# /!\ Remove all images
#echo "Remove all images"
#docker rmi $(docker images -q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment