温馨提示×

centos k8s如何挂载存储

小樊
61
2026-10-23 22:58:35
栏目: 云计算

在 CentOS 上的 Kubernetes(k8s) 中,“挂载存储”通常涉及 PV(PersistentVolume)+ PVC(PersistentVolumeClaim)+ Pod 挂载 三个部分。下面按常见场景给你讲清楚。


一、最常用方式:使用本地存储(HostPath / Local PV)

1️⃣ 使用 hostPath(仅测试环境)

直接把节点上的目录挂进 Pod

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
spec:
  containers:
  - name: app
    image: nginx
    volumeMounts:
    - name: data
      mountPath: /usr/share/nginx/html
  volumes:
  - name: data
    hostPath:
      path: /data/nginx

✅ 适合:

  • 单机测试
  • 学习 k8s

❌ 不适合:

  • 生产
  • 多节点调度

2️⃣ 使用 Local PV(推荐生产级本地盘)

(1)节点准备目录

mkdir -p /mnt/local-storage
chmod 777 /mnt/local-storage

(2)创建 PV

apiVersion: v1
kind: PersistentVolume
metadata:
  name: local-pv
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /mnt/local-storage
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - node1   # CentOS 节点名

(3)创建 PVC

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: local-pvc
spec:
  accessModes:
    - ReadWriteOnce
  storageClassName: local-storage
  resources:
    requests:
      storage: 10Gi

(4)Pod 使用

volumeMounts:
- name: data
  mountPath: /data
volumes:
- name: data
  persistentVolumeClaim:
    claimName: local-pvc

二、使用 NFS 存储(CentOS 常见)

1️⃣ CentOS 上搭建 NFS

yum install -y nfs-utils
mkdir /nfs
echo "/nfs *(rw,sync,no_root_squash)" > /etc/exports
systemctl enable --now nfs-server
exportfs -r

2️⃣ k8s 使用 NFS(无需 PV 插件)

方式一:直接挂载(简单)

volumes:
- name: nfs
  nfs:
    server: 192.168.1.100
    path: /nfs

方式二:PV + PVC(推荐)

apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-pv
spec:
  capacity:
    storage: 20Gi
  accessModes:
    - ReadWriteMany
  nfs:
    server: 192.168.1.100
    path: /nfs

三、使用 CentOS + 云盘(如 Ceph / Rook)

如果是 生产集群:

  • Ceph(Rook)
  • OpenEBS
  • Longhorn

这些都适合 CentOS + k8s

示例(Rook Ceph):

storageClassName: rook-ceph-block

四、查看挂载是否成功

kubectl get pv
kubectl get pvc
kubectl exec -it pod-name -- df -h

五、选型建议(非常重要)

场景 推荐
测试 hostPath
单机生产 Local PV
多节点共享 NFS / Ceph
云环境 云厂商 CSI

如果你能告诉我:

  • ✅ CentOS 版本
  • ✅ k8s 版本
  • ✅ 单节点还是集群
  • ✅ 想用本地盘 / NFS / 云盘

我可以直接给你一套能用的 yaml 文件。

0 踩