如何在 kubernetes pods 中以非 root 用户身份挂载 nfs 文件系统

如何在 kubernetes pods 中以非 root 用户身份挂载 nfs 文件系统

我在 CentOS 8 中的 kubernetes 集群(v1.18)pod 中挂载了一个 NFS 文件系统路径(nfs 安装在 Fedora 32 中),这是我的 pv yaml 定义:

apiVersion: v1
kind: PersistentVolume
metadata:
    name: nfs-jenkins-pv
    namespace: infrastrcuture
spec:
    capacity:
    storage: 8Gi
    accessModes:
    - ReadWriteOnce
    mountOptions:
    - vers=4.0
    - noresvport
    nfs:
    server: "192.168.31.2"
    path: "/home/dolphin/data/k8s/monitoring/infrastructure/jenkins"
    persistentVolumeReclaimPolicy: Retain

当我启动 pod 时,它显示此错误:

MountVolume.SetUp failed for volume "nfs-jenkins-pv" : mount failed: exit status 32 Mounting command: systemd-run Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/656dacd8-fcc9-44f1-a0c8-baa7eb5fa82e/volumes/kubernetes.io~nfs/nfs-jenkins-pv --scope -- mount -t nfs -o noresvport,vers=4.0 192.168.31.2:/home/dolphin/data/k8s/monitoring/infrastructure/jenkins /var/lib/kubelet/pods/656dacd8-fcc9-44f1-a0c8-baa7eb5fa82e/volumes/kubernetes.io~nfs/nfs-jenkins-pv Output: Running scope as unit: run-r5dc1ce59823746ffbbb18381cbec71cc.scope mount.nfs: Operation not permitted

我尝试像这样更改詹金斯文件夹的权限:

chmod 777 jenkins

但仍然不起作用。我可以使用 root 权限的命令行从本地机器挂载 nfs 文件系统,如下所示:

sudo mount -t nfs -o v3 192.168.31.2:/home/dolphin/data/k8s/monitoring/infrastructure/jenkins /mnt

但在 kuberentes 集群中,它始终是 root 用户,而 root 不是一个好的做法,可能会导致安全问题。我对导出文件进行了/etc/exports如下调整:

[dolphin@MiWiFi-R4CM-srv infrastructure]$ cat /etc/exports
/home/dolphin/data/k8s/monitoring/infrastructure/jenkins *(rw,no_root_squash)

我该怎么做才能让任何人都能挂载 nfs 文件系统?也许避免使用 root 用户。

答案1

使用 nfsv3 的工作原理:

apiVersion: v1
kind: PersistentVolume
metadata:
    name: nfs-jenkins-pv
    namespace: infrastrcuture
spec:
    capacity:
    storage: 8Gi
    accessModes:
    - ReadWriteOnce
    nfs:
    server: "192.168.31.2"
    path: "/home/dolphin/data/k8s/monitoring/infrastructure/jenkins"
    persistentVolumeReclaimPolicy: Retain

或者使用nfsv4,文件应该像这样写:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-jenkins-pv
  namespace: infrastrcuture
spec:
  capacity:
    storage: 8Gi
  accessModes:
    - ReadWriteOnce
  mountOptions:
    - vers=4.0
  nfs:
    server: "192.168.31.2"
    path: "/infrastructure/jenkins"
  persistentVolumeReclaimPolicy: Retain

并定义/etc/exports如下文件:

[dolphin@MiWiFi-R4CM-srv alertmanager]$ cat /etc/exports
/home/dolphin/data/k8s *(rw,fsid=0,sync,insecure_locks,insecure,no_root_squash)
/home/dolphin/data/k8s/infrastructure/jenkins *(rw,fsid=1000,sync,insecure_locks,insecure,no_root_squash)
/home/dolphin/data/k8s/monitoring/alertmanager *(rw,fsid=1001,sync,insecure_locks,insecure,no_root_squash)

相关内容