Last active
October 18, 2022 08:54
-
-
Save duruyao/a4b377ecdfd7a877cfe018ba7cd7a1b7 to your computer and use it in GitHub Desktop.
Automatically clean up exited docker containers periodically.
This file contains 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
#!/usr/bin/env bash | |
## date: 2022-01-14 | |
## author: duruyao@gmail.com | |
## desc: clean up exited docker containers | |
set -euo pipefail | |
tmp_path="${HOME}/.exited-containers" | |
log_path="${HOME}/.docker-container-cleaner.log" | |
docker ps -a | grep "Exited.* ago" >"${tmp_path}" | |
exited_container_info_head="$(docker ps -a | grep "CONTAINER ID")" | |
exited_container_ids=($(docker ps -a | grep "Exited.* ago" | sed "s/ .*/ /g")) | |
if docker ps -a | grep -q "Exited.* ago"; then | |
printf "%-25s ${exited_container_info_head}\n" "CLEANING TIME" >>"${log_path}" | |
for id in "${exited_container_ids[@]}"; do | |
time="$(TZ=UTC-8 date "+%Y-%m-%dT%H:%M:%S+08:00")" | |
if [ -n "${id}" ]; then | |
docker rm -f "${id}" && printf "%-25s %s\n" "${time}" "$(grep "${id}*" "${tmp_path}")" >>"${log_path}" || continue | |
fi | |
done | |
printf "\n--------------------------------------------------------------------------------\n\n" >>"${log_path}" | |
fi | |
rm -f "${tmp_path}" |
This file contains 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
#!/usr/bin/env bash | |
## date: 2022-01-14 | |
## author: duruyao@gmail.com | |
## desc: setup a cleaner which automatically cleans up exited docker containers every 1 hour | |
## desc: setup the docker-container-cleaner | |
set -euo pipefail | |
prefix="/usr/local/bin" | |
sudo curl -ksSL "https://gist.githubusercontent.com/duruyao/a4b377ecdfd7a877cfe018ba7cd7a1b7/raw/7a5a851119089d9035aedded8c09fdd23d2c5ee7/docker-container-cleaner.sh" -o "${prefix}"/docker-container-cleaner.sh | |
sudo chmod +x "${prefix}"/docker-container-cleaner.sh | |
auto_task="0 * * * * root ${prefix}/docker-container-cleaner.sh CRON=1" | |
if ! grep -Fxq "${auto_task}" /etc/crontab; then | |
echo "${auto_task}" | sudo tee -a /etc/crontab >/dev/null | |
fi | |
sudo service cron restart |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Setup
sudo bash -c "$(curl -fksSL https://gist.githubusercontent.com/duruyao/a4b377ecdfd7a877cfe018ba7cd7a1b7/raw/3e07d2a93432031a2fdee5f8b488fcc3d124a8fe/setup-docker-container-cleaner.sh)"