定时清理docker容器日志

场景:docker 容器启用一段时间之后日志会逐渐累积,越来越臃肿,可能高达几十个G,我们需要定期自动清理此容器日志

1.创建文件夹,创建文件写入命令,更改可执行权限:

mkdir -p /opt/docker-sh

cat > /opt/docker-sh/clean_docker_log.sh<< EOF
#!/bin/sh 
echo "======== start clean docker containers logs ========"  
logs=\$(find /var/lib/docker/containers/ -name *-json.log)  
for log in \$logs  
        do  
                echo "clean logs : \$log"  
                cat /dev/null > \$log  
        done  
echo "======== end clean docker containers logs ========"
EOF


cat > /opt/docker-sh/docker_log_size.sh<< EOF
#!/bin/sh

echo "======== docker containers logs file size ========"  

logs=\$(find /var/lib/docker/containers/ -name *-json.log)  

for log in \$logs  
        do  
             ls -lh \$log   
        done 

EOF

chmod +x docker_log_size.sh clean_docker_log.sh

2.跳转到可执行文件路径下:cd opt/docker-sh
3.查看日志大小:./docker_log_size.sh
4.清理所有日志:./clean_docker_log.sh
5.编辑定时任务:crontab -e
6.键入 a 进入编辑模式;
7.创建定时任务(每天晚上2点定期执行脚本清空容器日志):0 2 * * * /opt/docker-sh/clean_docker_log.sh(参考原文中有问题)
8.Ctrl+c 退出编辑模式
9.保存退出命令::wq(注意:带冒号),回车
10.查看定时任务:crontab -l

 

参考:

https://www.jianshu.com/p/9097e65046cc

https://www.zzzyk.com/show/b3e4be17b554b04d.htm#google_vignette

https://www.cnblogs.com/zhoading/p/11572630.html

https://blog.csdn.net/weixin_46094676/article/details/130049722

posted @ 2023-12-06 10:43  一看就懂  阅读(1306)  评论(0编辑  收藏  举报