DockerContainer often store all kinds of log, In the long run will take up small space,So how do you clean updocker日志呢?
我們有幾種方案:
The first is a temporary clean up,You can find the log position,直接刪除日志文件;
The second is regular maintenance,Using a script based on threshold execute the script to delete;
The third is to start the container log size set before,日志個數,After start the container according to the rules to deal with;
This blog recommend the third,Because this plan more reliable safe and reliable.
在linux上,容器日志一般存放在/var/lib/docker/containers/container_id/
下面, 以json.log
結尾的文件(業務日志)很大,Check the log file size script content is as follows:
#!/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
注意:Don't delete this file directly,Delete the log file will lead toDocker工作異常
如果docker容器正在運行,那麼使用rm -rf方式刪除日志後,通過df -h會發現磁盤空間並沒有釋放.原因是在Linux或者Unix系統中,通過rm -rf或者文件管理器刪除文件,將會從文件系統的目錄結構上解除鏈接(unlink).如果文件是被打開的(有一個進程正在使用),那麼進程將仍然可以讀取該文件,磁盤空間也一直被占用.正確姿勢是cat /dev/null > *-json.log,當然你也可以通過rm -rf刪除後重啟docker.接下來,Provide a clear log script content is as follows:
#!/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 ========"
但是,這樣清理之後,隨著時間的推移,容器日志會像雜草一樣,卷土重來.
When start the container to increase the size of a parameter is set the container log,And log drive
--log-driver json-file #日志驅動
--log-opt max-size=[0-9+][k|m|g] #文件的大小
--log-opt max-file=[0-9+] #文件數量
編輯文件/etc/docker/daemon.json
, Add the following log configuration
"log-driver":"json-file",
"log-opts": {
"max-size":"100m", "max-file":"3"}
max-size=100m,意味著一個容器日志大小上限是100M,
max-file=3,意味著一個容器有三個日志,分別是id+.json、id+1.json、id+2.json.
然後重啟docker守護進程
// 重啟docker守護進程
# systemctl daemon-reload
# systemctl restart docker
注意:設置的日志大小,只對新建的容器有效.
version: '3'
services:
myapi:
container_name: myapi
environment:
TZ: Asia/Shanghai
PYTHONIOENCODING: utf-8
logging:
driver: "json-file"
options:
max-size: "100m"
max-file: "3"
max-size=100m,意味著一個容器日志大小上限是100M,
max-file=3,意味著一個容器有三個日志,分別是id+.json、id+1.json、id+2.json.