Skip to content

Instantly share code, notes, and snippets.

@juanpabloaj
Created June 1, 2021 23:20
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 juanpabloaj/c16ac251ff04e1a19938a11f86969fe7 to your computer and use it in GitHub Desktop.
Save juanpabloaj/c16ac251ff04e1a19938a11f86969fe7 to your computer and use it in GitHub Desktop.
delete old containers
# /etc/systemd/system/docker_clean_old.service
[Unit]
Description=delete old containers
[Service]
CPUQuota=20%
TimeoutSec=3600
ExecStart=/bin/bash /root/opt/bin/docker_clean_old
#|/bin/bash
echo "searching for old containers ..."
for c in $(docker ps -q)
do
containerDate=$(docker inspect $c | jq '.[0].Created' | sed 's/"//g')
untilSeconds=${containerDate%.*}
asTimestamp=$(date -d $untilSeconds +%s)
secondsDiff=$(($(date +%s) - $asTimestamp))
if [ "$secondsDiff" -gt "7200" ]; then
echo "deleting container $c, his lifetime was $secondsDiff seconds"
docker rm -f $c
fi
done
echo "finishing old containers' deleting ..."
# /etc/systemd/system/docker_clean_old.timer
# systemctl start docker_clean_old.timer
# systemctl list-timers
[Unit]
Description=delete old containers every two hours
[Timer]
OnCalendar=0/2:00:00
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment