Last active
January 15, 2016 11:54
-
-
Save noniq/9edce9b315839cc7c699 to your computer and use it in GitHub Desktop.
A shell script to remove all exited docker containers that are older than a certain threshold. Customize the filter expression to restrict this to a certain group of containers. Should work on Linux and Mac OS.
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 | |
FILTER="--filter label=myapp" | |
THRESHOLD=$((7 * 24 * 60 * 60)) | |
NOW=$(date +%s) | |
USE_BSD_DATE=$(date -j >/dev/null 2>&1 && echo 1) | |
function date_to_timestamp { | |
if [[ $USE_BSD_DATE ]]; then | |
date -jf "%F %T %z" "$1" +%s | |
else | |
date --date="$date" +%s | |
fi | |
} | |
docker ps -a $FILTER --format "{{.ID}} {{.CreatedAt}}" | sed 's/ CET$//' | while IFS= read -r line; do | |
id=$(echo $line | sed 's/ .*$//') | |
date=$(echo $line | sed 's/^[^ ]* //') | |
timestamp=$(date_to_timestamp "$date") | |
if [[ $((NOW - timestamp)) -gt THRESHOLD ]]; then | |
docker rm $id | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment