Skip to content

Instantly share code, notes, and snippets.

@akerouanton
Last active June 1, 2016 22:59
Show Gist options
  • Save akerouanton/34eeca4d9e533d048ceed54eb3497cc7 to your computer and use it in GitHub Desktop.
Save akerouanton/34eeca4d9e533d048ceed54eb3497cc7 to your computer and use it in GitHub Desktop.
#!/bin/bash
CONTAINER_NAME=${CONTAINER_NAME:=docker-cleanup}
ps="`docker ps -a --format "{{.Names}}: {{.Status}}" | grep ${CONTAINER_NAME}`"
run_container () {
docker run -d \
--name docker-cleanup \
-v /var/run/docker.sock:/var/run/docker.sock:rw \
-v /var/lib/docker:/var/lib/docker:rw \
-e "KEEP_IMAGES='docker/compose,nir/composer'" \
-e "KEEP_CONTAINERS='docker/compose,nir/composer'" \
-e "DELAY_TIME=86400" \
-e "CLEAN_PERIOD=86400" \
meltwater/docker-cleanup:latest
}
remove_container () {
docker rm -f ${CONTAINER_NAME}
}
error () {
echo $1
exit 1
}
case "$1" in
start)
if [[ "$ps" == Up* ]]; then
error "docker-cleanup is already running."
fi
[ -n "$ps" ] && remove_container >/dev/null
run_container >/dev/null && echo "Container docker-cleanup started."
;;
stop)
[ -z "$ps" ] && error "Container docker-cleanup does not exists."
remove_container >/dev/null && echo "Container docker-cleanup stopped & removed."
;;
*)
error "$0: start|stop"
;;
esac
[Unit]
Description=Clean unused docker containers/images/volumes
Documentation=https://hub.docker.com/r/meltwater/docker-cleanup/
After=docker.service
Requires=docker.service
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/usr/local/bin/docker-cleanup start
ExecStop=/usr/local/bin/docker-cleanup stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment