Skip to content

Instantly share code, notes, and snippets.

@noniq
Last active January 15, 2016 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noniq/9edce9b315839cc7c699 to your computer and use it in GitHub Desktop.
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.
#!/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