1、编写自定义nginx Dockerifle
其中nginx-log-rotate.conf挂载到了阿里云的nas上

FROM nginx:1.24.0

# 安装crontab和logrotate
RUN apt-get update && apt-get install -y cron logrotate

# 创建文件夹
RUN mkdir /var/log/nginx/old_logs

# 复制nginx日志切割配置文件
#COPY nginx-log-rotate.conf /etc/nginx/nginx-log-rotate.conf

# 设置定时任务
RUN echo '59 23 * * * /usr/sbin/logrotate -f /etc/nginx/nginx-log-rotate.conf' | crontab -

# 启动nginx服务
CMD ["nginx", "-g", "daemon off;"]

2、打镜像

# docker build -t registry.ap-southeast-1.aliyuncs.com/bking/nginx:1.24.0 .
Sending build context to Docker daemon  403.3MB
Step 1/5 : FROM nginx@sha256:a8281ce42034b078dc7d88a5bfe6d25d75956aad9abba75150798b90fa3d1010
 ---> 2af0ea4a9556
Step 2/5 : RUN apt-get update && apt-get install -y cron logrotate
 ---> Using cache
 ---> 4f08b8614a50
Step 3/5 : RUN mkdir /var/log/nginx/old_logs
 ---> Running in 3e1f2111d92d
Removing intermediate container 3e1f2111d92d
 ---> e50a0a5470ca
Step 4/5 : RUN echo '59 23 * * * /usr/sbin/logrotate -f /etc/nginx/nginx-log-rotate.conf' | crontab -
 ---> Running in 2345650923fa
Removing intermediate container 2345650923fa
 ---> d071cd2dee73
Step 5/5 : CMD ["nginx", "-g", "daemon off;"]
 ---> Running in eaccd26b2e08
Removing intermediate container eaccd26b2e08
 ---> 10868cffb061
Successfully built 10868cffb061
Successfully tagged registry.ap-southeast-1.aliyuncs.com/bking/nginx:1.24.0

3、将镜像推送到镜像仓库

docker push registry.ap-southeast-1.aliyuncs.com/bking/nginx:1.24.0
The push refers to repository [registry.ap-southeast-1.aliyuncs.com/bking/nginx]
fdb834ea6835: Pushed 
095390bf435e: Pushed 
5ecea8c35c8f: Layer already exists 
fc78370c36ab: Layer already exists 
cfac81f0f09b: Layer already exists 
31c45124ce8c: Layer already exists 
98fa01fc3718: Layer already exists 
6f0f394de7c2: Layer already exists 
0cc1f0165626: Layer already exists 
1.24.0: digest: sha256:7da26ab26fb6a6b9883cf91346d606a155bc19cf1b905deab5ee2b2d6727c52a size: 2196

4、编写nginx-log-rotate.conf文件,文件内容那个如下

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

5、编写pod yaml文件并指定镜像仓库地址

---
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    k8s.kuboard.cn/displayName: front
  labels:
    k8s.kuboard.cn/layer: web
    k8s.kuboard.cn/name: front
  name: biking-front
  namespace: biking
  resourceVersion: '15725558'
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      k8s.kuboard.cn/layer: web
      k8s.kuboard.cn/name: front
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      annotations:
        kubectl.kubernetes.io/restartedAt: '2023-06-20T17:50:25+04:00'
      creationTimestamp: null
      labels:
        k8s.kuboard.cn/layer: web
        k8s.kuboard.cn/name: front
    spec:
      containers:
        - env:
            - name: TZ
              value: Asia/Shanghai
          image: 'registry.ap-southeast-1.aliyuncs.com/bking/nginx:1.24.0'
          imagePullPolicy: Always
          name: biking-front
          ports:
            - containerPort: 80
              name: gfds
              protocol: TCP
            - containerPort: 443
              name: sfdsf
              protocol: TCP
          resources: {}
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          volumeMounts:
            - mountPath: /etc/nginx
              name: volume-ine27
          workingDir: /etc/nginx
      dnsPolicy: ClusterFirst
      imagePullSecrets:
        - name: harbor-secret
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
        - name: volume-ine27
          persistentVolumeClaim:
            claimName: biking-oss

---
apiVersion: v1
kind: Service
metadata:
  annotations: {}
  labels:
    k8s.kuboard.cn/layer: web
    k8s.kuboard.cn/name: front
  name: biking-front
  namespace: biking
  resourceVersion: '530476'
spec:
  ports:
    - name: w8esy2
      port: 80
      protocol: TCP
      targetPort: 80
  selector:
    k8s.kuboard.cn/layer: web
    k8s.kuboard.cn/name: front
  sessionAffinity: None
  type: ClusterIP

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/cors-allow-headers: >-
      DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
    nginx.ingress.kubernetes.io/cors-allow-methods: 'GET, POST, PUT, DELETE, OPTIONS'
    nginx.ingress.kubernetes.io/cors-allow-origin: '*'
    nginx.ingress.kubernetes.io/cors-expose-headers: 'Content-Length,Content-Type'
    nginx.ingress.kubernetes.io/enable-cors: 'true'
  labels:
    k8s.kuboard.cn/layer: web
    k8s.kuboard.cn/name: front
  name: biking-front
  namespace: biking
  resourceVersion: '3237389'
spec:
  ingressClassName: nginx
  rules:
    - host: www.abc.com
      http:
        paths:
          - backend:
              service:
                name: front
                port:
                  number: 80
            path: /
            pathType: Prefix
  tls:
    - hosts:
        - www.abc.com

启动pod

kubectl apply -f nginx.yaml

6、登录pods对应的容器验证查看

# 验证定时任务是否成功添加
root@biking-front-7b4867d785-lczsq:/etc/nginx# crontab -l
59 23 * * * /usr/sbin/logrotate -f /etc/nginx/nginx-log-rotate.conf
# 验证logrotate是否成功安装
root@biking-front-7b4867d785-lczsq:/etc/nginx# /usr/sbin/logrotate --help
Usage: logrotate [OPTION...] <configfile>
  -d, --debug               Don't do anything, just test and print debug
                            messages
  -f, --force               Force file rotation
  -m, --mail=command        Command to send mail (instead of `/usr/bin/mail')
  -s, --state=statefile     Path of state file
      --skip-state-lock     Do not lock the state file
  -v, --verbose             Display messages during rotation
  -l, --log=logfile         Log file or 'syslog' to log to syslog
      --version             Display version information

Help options:
  -?, --help                Show this help message
      --usage               Display brief usage message
# 验证备份日志是否成功创建      
root@biking-front-b4867d785-lczsq:/etc/nginx# ls /var/log/nginx/old_logs/

到指定的时间验证日志是否已经切割
最后在测试的时候出现定时任务不能执行,最后改用执行文件启动
更改如下Dockerfile

FROM nginx:1.24.0

# 安装crontab和logrotate
RUN apt-get update && apt-get install -y cron logrotate

# 创建文件夹
RUN mkdir /var/log/nginx/old_logs

# 复制nginx日志切割配置文件
#COPY nginx-log-rotate.conf /etc/nginx/nginx-log-rotate.conf

# 添加定时任务到nginx目录
COPY nginx-crontab /etc/cron.d/nginx-crontab

# 设置文件权限
RUN chmod 0644 /etc/cron.d/nginx-crontab

# 设置定时任务
RUN crontab /etc/cron.d/nginx-crontab

# 设置定时任务
#RUN echo '59 23 * * * /usr/sbin/logrotate -f /etc/nginx/nginx-log-rotate.conf' | crontab -

# 启动nginx服务
CMD ["nginx", "-g", "daemon off;"]

Dockerfile文件将定时任务写到文件里
nginx-crontab文件内容如下

# 设置定时任务
59 23 * * * /usr/sbin/logrotate -f /etc/nginx/nginx-log-rotate.conf

最后我们可以根据我们的需求更改配置
至此就配置完毕

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐