问题
线上有个服务采用了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
在主机的hostpath目录下,会以pod name来创建出子目录,不同的pod使用不同的目录。
定期删除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