Kubernetes 存储 volume)
Kubernetes Volume 详解含命令 案例一、为什么需要 Volume问题Kubernetes 解决方案容器重启后数据丢失使用 Volume同 Pod 内容器共享数据emptyDirPod 访问节点文件hostPath多 Pod 共享持久数据NFS / PV / PVC⚠️容器文件系统是临时的Volume 才是数据的归宿二、emptyDir临时存储卷1️⃣ 核心特性属性说明生命周期与 Pod 一致数据持久性❌ 不持久跨节点❌典型用途缓存、临时文件、容器间通信2️⃣ YAML 示例yamlyaml# test-emptydir.yaml apiVersion: v1 kind: Pod metadata: name: test-emptydir spec: containers: - name: container-a image: alpine command: [/bin/sh, -c] args: - echo Hello emptyDir /cache/hello.txt sleep 3600 volumeMounts: - name: cache-volume mountPath: /cache volumes: - name: cache-volume emptyDir: {}3️⃣ 常用命令bashbashkubectl apply -f test-emptydir.yaml kubectl get pod test-emptydir kubectl exec test-emptydir -- cat /cache/hello.txt kubectl delete pod test-emptydir✅Pod 删除后数据消失三、hostPath节点级存储卷1️⃣ 核心特性属性说明生命周期依赖节点数据持久性✅节点未重装安全风险⚠️ 高典型用途日志、系统配置、调试2️⃣ YAML 示例yamlyaml# test-hostpath.yaml apiVersion: v1 kind: Pod metadata: name: test-hostpath spec: containers: - name: container-b image: alpine command: [/bin/sh, -c] args: - ls -l /host/tmp sleep 3600 volumeMounts: - name: host-tmp mountPath: /host/tmp readOnly: true volumes: - name: host-tmp hostPath: path: /tmp type: Directory3️⃣ 常用命令bashbashkubectl apply -f test-hostpath.yaml kubectl exec test-hostpath -- ls /host/tmp⚠️生产环境建议使用readOnly: true限制hostPath.path配合PodSecurityPolicy / PSA四、NFS共享持久存储1️⃣ 核心特性属性说明跨节点✅多 Pod 共享✅持久化✅访问模式ReadWriteMany五、NFS PV PVC 实战1️⃣ 前提条件NFS Server192.168.1.100导出目录/nfs/data节点已安装nfs-utils2️⃣ PersistentVolumePVyamlyaml# nfs-pv.yaml apiVersion: v1 kind: PersistentVolume metadata: name: nfs-pv spec: capacity: storage: 10Gi accessModes: - ReadWriteMany persistentVolumeReclaimPolicy: Retain nfs: server: 192.168.1.100 path: /nfs/data3️⃣ PersistentVolumeClaimPVCyamlyaml# nfs-pvc.yaml apiVersion: v1 kind: PersistentVolumeClaim metadata: name: nfs-pvc spec: accessModes: - ReadWriteMany resources: requests: storage: 5Gi4️⃣ Pod 使用 NFS PVCyamlyaml# nfs-pod.yaml apiVersion: v1 kind: Pod metadata: name: nfs-test-pod spec: containers: - name: app image: alpine command: [/bin/sh, -c] args: - echo NFS Data /data/test.txt sleep 3600 volumeMounts: - name: nfs-storage mountPath: /data volumes: - name: nfs-storage persistentVolumeClaim: claimName: nfs-pvc5️⃣ 操作命令汇总bashbashkubectl apply -f nfs-pv.yaml kubectl apply -f nfs-pvc.yaml kubectl apply -f nfs-pod.yaml kubectl get pv kubectl get pvc kubectl exec nfs-test-pod -- cat /data/test.txt✅Pod 删除后NFS 数据仍然存在六、三种 Volume 对比总结类型持久化跨节点多 Pod 共享风险emptyDir❌❌✅同 Pod低hostPath✅❌❌高NFS✅✅✅低