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。

相关推荐
tryCbest1 小时前
CentOS部署Docker容器
linux·docker·centos
qyhua2 小时前
【Linux运维实战】彻底修复 CVE-2011-5094 漏洞
linux·运维·安全
坠金2 小时前
linux/centos迁移conda文件夹
linux·centos·conda
纳于大麓3 小时前
Kotlin基础语法
linux·windows·kotlin
九皇叔叔3 小时前
Linux Shell 正则表达式中的 POSIX 字符集:用法与实战
linux·运维·正则表达式
東雪蓮☆4 小时前
K8s 平滑升级
linux·运维·云原生·kubernetes
---学无止境---5 小时前
Linux中进程创建和缓存对象初始化fork_init、proc_caches_init和buffer_init
linux
惘嘫、冋渞5 小时前
CentOS 7 下 Nginx 编译后热重启方案
chrome·nginx·centos
qq_183802875 小时前
Linux内核idr数据结构使用
linux·运维·服务器
码农-小林5 小时前
使用leaflet库加载服务器离线地图瓦片(这边以本地nginx服务器为例)
运维·服务器·nginx