本地存储卷之 hostPath 进阶使用 ¶
适用场景 ¶
- 节点监控 Agent 收集系统指标
- pod内与集群节点目录映射(pod中容器想访问节点上数据,例如监控,只有监控访问到节点主机文件才能知道集群节点主机状态)
- 特殊设备文件挂载(如GPU)
- 跨 Pod 共享宿主机目录
- 缺点:如果集群节点挂掉,控制器在另一个集群节点拉起容器,数据就会变成另一台集群节点主机的了(无法实现数据共享)
安全配置 ¶
volumes:
- name: data
hostPath:
path: /opt/hostpath
type: Directory # 严格限制类型
权限控制 ¶
宿主机目录权限设置
chmod 755 /opt/hostpath && chown 1000:1000 /opt/hostpath
实践 ¶
1. 创建资源清单 volume-emptydir.yml, 选择调度在 k8sworker001 节点
apiVersion: v1
kind: Pod
metadata:
name: volume-hostpath
spec:
nodeName: k8sworker001
containers:
- name: busybox
image: busybox
imagePullPolicy: IfNotPresent
command: ["/bin/sh","-c","echo haha > /data/1.txt ; sleep 600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
hostPath:
path: /opt/hostpath
type: Directory # 严格限制类型
2. 基于 yaml 文件创建 pod, 选择调度在 k8sworker001 节点
[root@k8smaster001 hostpath]# kubectl apply -f volume-hostpath.yml
pod/volume-hostpath created
3. 查看 pod 启动情况,发现失败 需要去节点手动创建 /opt/hostpath 挂载目录
[root@k8smaster001 hostpath]# kubectl describe pod |tail -n 10
ConfigMapOptional: <nil>
DownwardAPI: true
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedMount 36s (x8 over 99s) kubelet MountVolume.SetUp failed for volume "data" : hostPath type check failed: /opt/hostpath is not a directory
4. 去绑定节点创建本地目录存储目录 /opt/hostpath
[root@k8sworker001 ~]# mkdir /opt/hostpath
5. 再次查看日志,发现成功启动
[root@k8smaster001 hostpath]# kubectl describe pod |tail -n 10
ConfigMapOptional: <nil>
DownwardAPI: true
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Pulling 2s kubelet Pulling image "busybox"
6. 验证 pod 所在机器上的挂载文件
[root@k8sworker001 hostpath]# pwd && ls
/opt/hostpath
1.txt
[root@k8sworker001 hostpath]# cat 1.txt
haha
生产经验 ¶
- 🚫 避免使用绝对路径,建议通过 PV 抽象
- 🚫 跨节点部署需配合 nodeSelector