-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdockercleanup.sh
More file actions
executable file
·117 lines (109 loc) · 2.34 KB
/
Copy pathdockercleanup.sh
File metadata and controls
executable file
·117 lines (109 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/bin/bash
# =========== Print Usage ===========
printUsage()
{
printf "Usage: "
printf "dockercleanup [OPTIONS]"
printf "\n dockercleanup [-h | --help]"
printf "\n\nA script to cleanup docker images and non-running containers.\n"
printf "\nOptions:\n"
printf "\n-a, --all\t\tDelete all images."
printf "\n-o, --only-untagged\tDelete only Untagged images."
printf "\n--delete-cont\t\tDefault is false.Set to 'true' to delete all the non-running containers."
printf "\n\n"
}
# ===================================
checkExitStatus()
{
$@ > /dev/null 2>&1
local status=$?
return $status
}
# ===================================
runCommand()
{
$@
return $?
}
# ===================================
deleteImages()
{
if [[ $1 ]];then
runCommand docker rmi -f $1
printf "Done.\n"
else
printf "No images to delete.\n"
fi
}
# ===================================
# check if docker is installed on the node
checkExitStatus docker --version
if [[ $? -ne 0 ]];
then
printf "Docker is not installed, please install docker\n"
exit 1
fi
# check if docker daemon is running on the node
checkExitStatus docker version
if [[ $? -ne 0 ]];
then
printf "Cannot connect to the Docker daemon. Is the docker daemon running on this host?\n"
exit 1
fi
# Check if any options are passed.
if [[ $# == 0 ]];
then
printUsage
exit 0
fi
# read the options
while [[ $# > 0 ]]
do
key="$1"
case $key in
-h|--help)
printUsage
shift
;;
-a|--all)
DELETE_ALL=true
shift
;;
-o|--only-untagged)
DELETE_UNTAGGED=true
shift
;;
--delete-cont)
DELETE_CONT=true
shift
shift
;;
*)
printf "Invalid Command\n"
printUsage
;;
esac
done
# Delete the containers
if [[ "$DELETE_CONT" = true ]];
then
printf "Deleting stopped containers...\n"
containers=$(docker ps -q -f status=exited)
if [[ $containers ]]; then
runCommand docker rm $containers
printf "Done.\n"
else
printf "No containers to delete.\n"
fi
fi
# Delete the images.
if [[ "$DELETE_ALL" = true ]];
then
printf "Deleting all images...\n"
image=$(docker images -a -q)
deleteImages $image
elif [[ "$DELETE_UNTAGGED" = true ]]; then
printf "Deleting untagged images...\n"
image=$(docker images --filter "dangling=true" -q)
deleteImages $image
fi