欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > Clean Docker Images and Container by Cron Job

Clean Docker Images and Container by Cron Job

2025/9/16 8:24:55 来源:https://blog.csdn.net/wish366/article/details/144102040  浏览:    关键词:Clean Docker Images and Container by Cron Job

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

#!/bin/bash# 找到所有状态不正常的容器
containers=$(docker ps -a --filter "status=exited" --filter "status=dead" --format "{{.ID}}")if [ -z "$containers" ]; thenecho "No containers to clean."
elseecho "Cleaning up the following containers:"echo "$containers"echofor container in $containers; doecho "Deleting container $container"docker rm -f $containerdone
fi# 设置 Cron Job:crontab -e

2. Create a delete_docker_images.sh to delete images with keyword.

#!/bin/bash# 检查是否提供了关键词参数
if [ "$#" -ne 1 ]; thenecho "Usage: $0 <keyword>"exit 1
fi# 关键词参数
KEYWORD=$1# 找到所有包含关键词的镜像
images=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep ${KEYWORD})if [ -z "$images" ]; thenecho "No images found with keyword: ${KEYWORD}"
elseecho "Images to be deleted:"echo "$images"echofor image in $images; doecho "Deleting image $image"docker rmi -f $imagedone
fi

3. Create a run_clean_docker.sh to run these shell command as above.

#!/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>&1echo "[$(date '+%Y-%m-%d %H:%M:%S')] End" >> ${LOGFILE}
echo "" >> ${LOGFILE}

4. Set a cron job

4.1 crontab -e


# 第一颗星表示分钟(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

[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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词