k8s

同节点多个pod hostPath目录一致问题解决

问题

线上有个服务采用了hostPath方式存储日志,单个节点跑了2个pod,导致这两个pod的日志完全一致,因为读取的是同一个目录。

解决

有两种方法:第一种方法是仍然使用hostPath,第二种方法是使用PVC,同时从deployment切换到statefulset。这里采用了第一种。

添加env,使用subPathExpr参数。

spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:stable-alpine
          env:
          - name: POD_NAME
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          volumeMounts:
            - name: nginx-storage
              mountPath: /usr/share/nginx/html
              subPathExpr: $(POD_NAME)
      volumes:
        - name: nginx-storage
          hostPath:
            path: /opt/wgh
            type: DirectoryOrCreate

file

在主机的hostpath目录下,会以pod name来创建出子目录,不同的pod使用不同的目录。

file

定期删除hostpath下未使用的目录。

#!/bin/bash

# 定义要清理的目录
LOG_DIR="/var/logs/nginx"

# 定义日志文件
LOG_FILE="/var/log/cleanup_$(date +%Y%m%d).log"

# 查找并删除3天以前的目录,同时记录日志
find "$LOG_DIR" -type d -mtime +2 -print | while read -r dir; do
    echo "Deleting directory: $dir at $(date)" >> "$LOG_FILE"
    rm -rf "$dir"
done

chmod +x cleanup.sh

crontab -e 
# 每天凌晨 2 点执行
0 2 * * * /root/leanup.sh
分类: k8s
0 0 投票数
文章评分
订阅评论
提醒
guest

0 评论
最旧
最新 最多投票
内联反馈
查看所有评论

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部
0
希望看到您的想法,请您发表评论x