K8S nginx pod结合cronJob实现日志按天切割 —— 筑梦之路

前言

nginx的官方镜像都是把日志重定向到标准输出,如果没有特别需求,已经能满足大多数的使用。

这里我主要对官方镜像进行改造,添加logrotate,结合cronJob来实现nginx日志的自动轮转,以方便排查故障问题。

编写Dockerfile构建镜像

1. 编写Dockerfile文件

bash 复制代码
# Dockerfile文件
cat Dockerfile

FROM nginx:1.26.2-alpine-slim
RUN apk update && apk add logrotate \
    && unlink /var/log/nginx/access.log \
    && unlink /var/log/nginx/error.log \
    && rm -rf /var/cache/apk/*
COPY nginx /etc/logrotate.d/nginx

# logrotate配置文件
cat nginx

/var/log/nginx/*.log {
  su root root
  nocompress
  daily
  copytruncate
  create
  notifempty
  rotate 180
  missingok
  dateext
  postrotate
    /bin/kill -HUP `cat /var/run/nginx.pid 2> /dev/null` 2> /dev/null || true
  endscript
}

2. 构建双架构镜像

bash 复制代码
# 如何构建多架构镜像,参考其他文章,这里把主要的命令记录在此

docker buildx build --platform=linux/amd64,linux/arm64 -t nginx:1.26.2-alpine_logrotate_root_20241029 -f Dockerfile . --push

K8S部署cronJob资源

这里主要是cronJob资源的yaml文件,其他和常规使用区别不大

bash 复制代码
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: nginx-logs-rotate
  namespace: merry
spec:
  schedule: "59 23 * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: nginx-logs-rotate
            image: nginx:1.26.2-alpine_logrotate_root_20241029
            command: ["sh", "-c", "/usr/sbin/logrotate -vf /etc/logrotate.d/nginx"]
            securityContext:
              runAsUser: 0
            volumeMounts:
            - name: nginx-logs
              mountPath: /var/log/nginx
          volumes:
          - name: nginx-logs
            persistentVolumeClaim:
              claimName: nginx-logs-pvc
          restartPolicy: OnFailure

注意事项:

  1. 部署的nginx pod镜像和cronJob镜像需要一致;

  2. 镜像时区要准确;

  3. nginx配置文件最好是自定义,这里我使用了root用户运行nginx。

相关推荐
Everbrilliant897 分钟前
Ubuntu系统下交叉编译Android的X265库
linux·运维·ubuntu·x265交叉编译·android x265·ffmpeg x265
我不要放纵15 分钟前
LVS集群搭建
linux·服务器·lvs
阿巴~阿巴~20 分钟前
自主Shell命令行解释器
linux·运维·服务器
许白掰20 分钟前
Linux入门篇学习——借助 U 盘或 TF 卡拷贝程序到开发板上
linux·学习·借助 u 盘拷贝程序到开发板上·借助 tf卡拷贝程序到开发板上
David爱编程30 分钟前
K8s 的 Namespace 到底解决了什么问题?
云原生·容器·kubernetes
婷儿z36 分钟前
Kubernetes 架构原理与集群环境部署
容器·架构·kubernetes
岚天start1 小时前
Kubernetes(k8s)中命令行查看Pod所属控制器之方法总结
kubernetes·k8s·pod·daemonset·deployment·statefulset
YuTaoShao2 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
退役小学生呀2 小时前
十五、K8s可观测能力:日志收集
linux·云原生·容器·kubernetes·k8s
van叶~2 小时前
Linux探秘坊-------15.线程概念与控制
linux·运维·服务器