Kubernetes - 日志挂载方案
2021-10-09
方案1 (k8s内置)
https://kubernetes.io/zh/docs/concepts/storage/volumes/
FEATURE STATE: Kubernetes v1.17 [stable]
使用 subPathExpr 字段可以基于 Downward API 环境变量来构造 subPath 目录名。 subPath 和 subPathExpr 属性是互斥的。在这个示例中,Pod 使用 subPathExpr 来 hostPath 卷 /var/log/pods 中创建目录 pod1。 hostPath 卷采用来自 downwardAPI 的 Pod 名称生成目录名。 宿主目录 /var/log/pods/pod1 被挂载到容器的 /logs 中。
apiVersion: v1
kind: Pod
metadata:
name: pod1
spec:
containers:
- name: container1
env:
- name: POD_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.name
image: busybox
command: [ "sh", "-c", "while [ true ]; do echo 'Hello'; sleep 10; done | tee -a /logs/hello.txt" ]
volumeMounts:
- name: workdir1
mountPath: /logs
subPathExpr: $(POD_NAME)
restartPolicy: Never
volumes:
- name: workdir1
hostPath:
path: /var/log/pods
方案2(软链)
apiVersion: v1
kind: Pod
metadata:
name: pod1
spec:
containers:
- name: container1
env:
- name: POD_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.name
image: busybox
lifecycle:
postStart:
exec:
command:
- /bin/sh
- -c
- mkdir -p /var/log/${YQN_POD_NAME} && rm -rf /opt/web/ws-${APP_PORT}/logs
&& ln -s /var/log/${YQN_POD_NAME} /opt/web/ws-${APP_PORT}/logs
command: [ "sh", "-c", "while [ true ]; do echo 'Hello'; sleep 10; done | tee -a /logs/hello.txt" ]
volumeMounts:
- name: workdir1
mountPath: /logs
subPathExpr: $(POD_NAME)
restartPolicy: Never
volumes:
- name: workdir1
hostPath:
path: /var/log/pods