Created
April 17, 2015 19:09
-
-
Save ric03uec/cb93a71e773b94345c5a to your computer and use it in GitHub Desktop.
remove docker containers based on time
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 -e | |
if [[ $# > 0 ]]; then | |
export MAX_CONTAINER_UPTIME_MINS=$1 | |
else | |
export MAX_CONTAINER_UPTIME_MINS=30 | |
fi | |
echo "Removing containers older than: $MAX_CONTAINER_UPTIME_MINS minutes" | |
export container_ids="" | |
export remove_container_ids="" | |
get_containers() { | |
echo "getting containers" | |
container_ids=$(sudo docker ps -aq) | |
} | |
filter_containers() { | |
for container in $container_ids; do | |
started_at_string=$(docker inspect $container | grep StartedAt | awk '{print $2}') | |
# remove outermost double quotes | |
started_at_string=$(echo "$started_at_string" | tr -d '"') | |
# converting string to bash date | |
started_at_time=$(date --date=$started_at_string +%s) | |
current_time=$(date +"%s") | |
time_diff_secs=$(($current_time-$started_at_time)) | |
time_diff_mins=$(($time_diff_secs/60)) | |
if [[ $time_diff_mins -gt $MAX_CONTAINER_UPTIME_MINS ]]; then | |
remove_container_ids="$remove_container_ids $container" | |
fi | |
done | |
} | |
remove_containers() { | |
if [[ ! -z $remove_container_ids ]]; then | |
remove_count=$(echo "$remove_container_ids" | wc -w) | |
echo "removing [$remove_count] containers $remove_container_ids" | |
container_remove_cmd="sudo docker rm $remove_container_ids" | |
$container_remove_cmd | |
else | |
echo "no containers to remove" | |
fi | |
} | |
get_containers | |
filter_containers | |
remove_containers |
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
$ ./clean.sh 10 //remove containers older than 10 mins | |
$ ./clean.sh //remove containers older than 30 mins(default) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment