Clean Docker Images and Container by Cron Job

1.Cretae a clean_docker_containers.sh to clean containers (status: exited, dead)

bash 复制代码
#!/bin/bash

# 找到所有状态不正常的容器
containers=$(docker ps -a --filter "status=exited" --filter "status=dead" --format "{{.ID}}")

if [ -z "$containers" ]; then
    echo "No containers to clean."
else
    echo "Cleaning up the following containers:"
    echo "$containers"
    echo

    for container in $containers; do
        echo "Deleting container $container"
        docker rm -f $container
    done
fi

# 设置 Cron Job:crontab -e
  1. Create a delete_docker_images.sh to delete images with keyword.
bash 复制代码
#!/bin/bash

# 检查是否提供了关键词参数
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <keyword>"
    exit 1
fi

# 关键词参数
KEYWORD=$1

# 找到所有包含关键词的镜像
images=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep ${KEYWORD})

if [ -z "$images" ]; then
    echo "No images found with keyword: ${KEYWORD}"
else
    echo "Images to be deleted:"
    echo "$images"
    echo

    for image in $images; do
        echo "Deleting image $image"
        docker rmi -f $image
    done
fi
  1. Create a run_clean_docker.sh to run these shell command as above.
bash 复制代码
#!/bin/bash

# SET PATH
cd /your-parth/Docker

# 定义日志文件
LOGFILE="./cron.log"

# 记录时间和作者
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Delete Docker Images and Container Script executed" >> ${LOGFILE}

# 运行原先的脚本,并将输出写入日志
./delete_docker_images.sh /your-keyword/ >> ${LOGFILE} 2>&1
./clean_docker_containers.sh >> ${LOGFILE} 2>&1

echo "[$(date '+%Y-%m-%d %H:%M:%S')] End" >> ${LOGFILE}
echo "" >> ${LOGFILE}
  1. Set a cron job

4.1 crontab -e

bash 复制代码
# 第一颗星表示分钟(0-59)第二颗星表示小时(0-23)第三颗星表示一个月中的天(1-31)
# 第四颗星表示月份(1-12)第五颗星表示一周中的天(0-7,星期天可以是0或7)
# 每天8時定期清理 docker images by keyword & container
0 8 * * * /your-path/Docker/run_clean_docker.sh

4.2 cron.log

html 复制代码
[2024-11-28 08:00:01] Delete Docker Images and Container Script executed
No images found with keyword: /ccs/
No containers to clean.
[2024-11-28 08:00:01] End
相关推荐
zzzsde1 分钟前
【Linux】基础开发工具(2):vim补充说明&&gcc/g++编译器
linux·运维·服务器
河南博为智能科技有限公司7 分钟前
动环监控终端-守护变电站安全运行的智能核心
运维·服务器·网络·物联网
tzhou6445211 分钟前
Nginx 性能优化与防盗链配置
运维·nginx·性能优化
热爱学习的小怪兽25 分钟前
Docker容器的一些总结
运维·docker·容器
清云逸仙36 分钟前
AI Prompt 工程最佳实践:打造结构化的Prompt
人工智能·经验分享·深度学习·ai·ai编程
要站在顶端44 分钟前
基于 curl 实现 Jenkins 上传制品到 JFrog Artifactory
运维·ci/cd·jenkins
杨德杰1 小时前
Ubuntu设置VNC远程桌面
linux·运维·ubuntu
❀͜͡傀儡师1 小时前
Docker一键部署Nexus Terminal,高颜值SSH新体验
docker·容器·ssh
写代码的学渣2 小时前
Ubuntu/麒麟默认锁定root账户
linux·运维·ubuntu
TH_12 小时前
腾讯云-(10)-宝塔面板-Docker下安装Elasticsearch
elasticsearch·docker·容器