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。

相关推荐
魔道不误砍柴功19 分钟前
Quarkus 2025终极指南:GraalVM Native Image如何让Java在K8s中起飞?
java·开发语言·kubernetes
yuren_xia22 分钟前
Linux 系统中 `echo`、`cat`、`tail`、`grep` 四个常用命令介绍
linux·运维·chrome
漫谈网络31 分钟前
DDoS防御与流量优化
linux·网络·iptables·ddos·netfilter·syn攻击·流量审计
黎明鱼儿1 小时前
高可用架构:Keepalived、Nginx与Docker深度解析
nginx·docker·架构
楚灵魈2 小时前
[Linux]从零开始的ARM Linux交叉编译与.so文件链接教程
linux·arm开发
怪兽也会哭哭2 小时前
项目部署至服务器 :如何在Nginx反向代理中将HTTP/HTTPS混合请求处理?让我来看看~
服务器·nginx·http
杰瑞的猫^_^2 小时前
【Linux】TCP协议
linux·网络·网络协议·tcp/ip
ylatin2 小时前
Elasticsearch 索引 es
大数据·linux·elasticsearch
浅安的邂逅2 小时前
Linux Makefile-概述、语句格式、编写规则、多文件编程、Makefile变量分类:自定义变量、预定义变量
linux·c语言·vim·makefile·gcc
tjsoft3 小时前
asm汇编字符串操作
linux·运维·汇编