最近在做nginx的日志按天分割,由于我们的nginx是运行在docker容器中,所以需要一个支持的日志切割的nginx镜像,镜像链接:https://pan.baidu.com/s/18heZtGSDflYaPeVVC0RnDg?pwd=void
logrotate使用方式参考这篇文章:https://blog.csdn.net/weixin_43702146/article/details/132146978
-
首先运行需要保存为镜像的容器,可以使用 docker run 命令来运行容器,例如交互运行一个nginx容器:
docker run --name nginx-test -it -p 8082:80 --rm nginx:latest bash
-
然后,在容器中执行必要的更改,例如,安装需要的软件包等
# 备份仓库 mv /etc/apt/sources.list /etc/apt/sources.list.bak # 写入加速地址 echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye main contrib non-free" >/etc/apt/sources.list echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye-updates main contrib non-free" >>/etc/apt/sources.list echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye-backports main contrib non-free" >>/etc/apt/sources.list echo "deb http://mirrors.tuna.tsinghua.edu.cn/debian-security bullseye-security main contrib non-free" >>/etc/apt/sources.list # 更新软件仓库 apt-get update # 安装ps命令 apt-get install procps # 安装vim apt-get install vim # 安装curl apt-get install curl # 安装ping apt-get install iputils-ping # 安装logrotate cron apt-get install logrotate cron # 配置ll(需要cd到根目录执行) echo "alias ll='ls -l'" >> ~/.bashrc && source ~/.bashrc # 配置时区 echo 'Asia/Shanghai' >/etc/timezone # 配置时间 ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
-
修改下默认的
/etc/logrotate.d/nginx
文件/var/log/nginx/*.log { daily missingok notifempty rotate 7 delaycompress create dateext sharedscripts postrotate if [ -f /var/run/nginx.pid ]; then kill -USR1 `cat /var/run/nginx.pid` fi endscript }
-
如果是第一次使用,修改下默认的状态文件
vim /var/lib/logrotate/status
:logrotate state -- version 2 "/var/log/nginx/error.log" 2023-8-7-00:00:00 "/var/log/nginx/access.log" 2023-8-7-00:00:00
-
启动定时任务并进行配置
crontab -e # 添加如下内容 59 23 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginx
-
然后在宿主机运行以下命令将容器保存为新的镜像(不要stop掉容器)
docker commit --change='CMD ["nginx", "-g", "daemon off;"]' a01f29080abd nginx-logrotate:latest
-
将镜像上传至仓库或者保存,这里保存镜像为tar
docker save -o nginx-logrotate.tar nginx-logrotate:latest
注意: 由于我们在启动容器时使用的是 /bin/bash
,这样通过commit
制作的镜像的CMD
就是bash
,这是非阻塞的(新容器启动后一闪而过,然后就exited了),这不是我们所期望的,解决方案如下:
参考:https://www.cnblogs.com/sylvia-liu/p/14647866.html
- 以在
commit
时使用--change='CMD ["nginx", "-g", "daemon off;"]'
重新指定一下CMD
- 在
docker run --name nginx-test -it -p 8082:80 --rm nginx:latest bash
时去除-it、--rm、bash
,通过exec
进入该容器,然后进行常规commit