Last active
September 2, 2024 04:32
-
-
Save duruyao/a4b377ecdfd7a877cfe018ba7cd7a1b7 to your computer and use it in GitHub Desktop.
Automatically cleaning up exited docker containers periodically.
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
| #!/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 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
| #!/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 cp docker-container-cleaner.sh /usr/local/bin/docker-container-cleaner.sh | |
| sudo chmod +x /usr/local/bin/docker-container-cleaner.sh | |
| auto_task="0 * * * * root /usr/local/bin/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 |
Author
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)"