1. 程式人生 > 其它 >k8s 資料卷hostPath卷

k8s 資料卷hostPath卷

k8s-資料卷hostPath卷

1. 資料卷hostPath卷

  • hostPath卷:掛載Node節點本地檔案系統(Pod所在節點)上檔案或者目錄到Pod中的容器。

  • 應用場景:Pod中容器需要訪問宿主機檔案

  • 示例:

    apiVersion: v1
    kind: Pod
    metadata:
      name: my-hostpath
    spec:
      containers: 
      - name: busybox
        image: busybox
        args:
        - /bin/sh
        - -c
        - sleep 36000
        volumeMounts:
        - name: data
          mountPath: /data
      volumes:
      - name: data
        hostPath:
          path: /tmp
          type: Directory
    

    ​ 示例:將宿主機/tmp目錄掛載到容器/data目錄

2. 案例

2.1 編寫配置檔案

  • 建立編寫配置檔案目錄

    [root@k8s-master yaml]# mkdir -p hostPath/
    [root@k8s-master yaml]# cd hostPath/
    [root@k8s-master hostPath]# ll
    總用量 0
    
  • 編寫配置檔案

    [root@k8s-master hostPath]# vim hostpath.yaml
    [root@k8s-master hostPath]# cat hostpath.yaml
    apiVersion: v1
    kind: Pod
    metadata:
      name: my-hostpath
    spec:
      containers: 
      - name: busybox
        image: busybox
        args:
        - /bin/sh
        - -c
        - sleep 36000
        volumeMounts:
        - name: data
          mountPath: /data
      volumes:
      - name: data
        hostPath:
          path: /tmp
          type: Directory
    

2.2 啟動服務

[root@k8s-master hostPath]# kubectl apply -f hostpath.yaml 
pod/my-hostpath created

2.3 檢視服務是否啟動

[root@k8s-master hostPath]# kubectl get pods -o wide
NAME                 READY   STATUS    RESTARTS   AGE     IP               NODE        NOMINATED NODE   READINESS GATES
configmap-demo-pod   1/1     Running   0          2d      10.244.107.209   k8s-node3   <none>           <none>
my-hostpath          1/1     Running   0          4m28s   10.244.107.211   k8s-node3   <none>           <none>
secret-demo-pod      1/1     Running   0          41h     10.244.107.210   k8s-node3   <none>           <none>

2.4 驗證資料

我們可以看到節點在node3上面,我們去node3節點/tmp/目錄下載建立一個檔案做測試”test.txt“

  • 在node3上/tmp/目錄下建立”test.txt“檔案

    [root@k8s-node3 ~]# cd /tmp/
    [root@k8s-node3 tmp]# ls
    [root@k8s-node3 tmp]# touch test.txt
    [root@k8s-node3 tmp]# ls
    test.txt
    
  • 進入docker容器,驗證是否被引入

    [root@k8s-master hostPath]# kubectl exec -it my-hostpath -- /bin/sh 
    / # ls  /data/
    test.txt