配置 Pod 使用捲進行儲存

本頁面展示如何配置 Pod 使用 Volume 進行儲存。

容器的檔案系統只在容器的生命週期記憶體在。因此,當容器終止並重新啟動時,檔案系統更改將丟失。為了獲得獨立於容器的更一致的儲存,可以使用 Volume。這對於有狀態應用程式,例如鍵值儲存(如 Redis)和資料庫尤其重要。

準備工作

你需要有一個 Kubernetes 叢集,並且 kubectl 命令列工具已配置為與你的叢集通訊。建議在至少有兩個不作為控制平面主機的節點的叢集上執行本教程。如果你還沒有叢集,可以使用 minikube 建立一個叢集,或者使用以下 Kubernetes 演練場之一

要檢查版本,請輸入 kubectl version

為 Pod 配置 Volume

在此練習中,你將建立一個執行一個容器的 Pod。此 Pod 具有 emptyDir 型別的 Volume,該 Volume 在 Pod 的整個生命週期內都存在,即使容器終止並重新啟動。以下是 Pod 的配置檔案

apiVersion: v1
kind: Pod
metadata:
  name: redis
spec:
  containers:
  - name: redis
    image: redis
    volumeMounts:
    - name: redis-storage
      mountPath: /data/redis
  volumes:
  - name: redis-storage
    emptyDir: {}
  1. 建立 Pod

    kubectl apply -f https://k8s.io/examples/pods/storage/redis.yaml
    
  2. 驗證 Pod 的容器正在執行,然後檢視 Pod 的更改

    kubectl get pod redis --watch
    

    輸出如下:

    NAME      READY     STATUS    RESTARTS   AGE
    redis     1/1       Running   0          13s
    
  3. 在另一個終端中,獲取執行中容器的 Shell

    kubectl exec -it redis -- /bin/bash
    
  4. 在你的 Shell 中,進入 /data/redis,然後建立一個檔案

    root@redis:/data# cd /data/redis/
    root@redis:/data/redis# echo Hello > test-file
    
  5. 在你的 Shell 中,列出正在執行的程序

    root@redis:/data/redis# apt-get update
    root@redis:/data/redis# apt-get install procps
    root@redis:/data/redis# ps aux
    

    輸出類似於:

    USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
    redis        1  0.1  0.1  33308  3828 ?        Ssl  00:46   0:00 redis-server *:6379
    root        12  0.0  0.0  20228  3020 ?        Ss   00:47   0:00 /bin/bash
    root        15  0.0  0.0  17500  2072 ?        R+   00:48   0:00 ps aux
    
  6. 在你的 Shell 中,終止 Redis 程序

    root@redis:/data/redis# kill <pid>
    

    其中 <pid> 是 Redis 程序 ID (PID)。

  7. 在你的原始終端中,檢視 Redis Pod 的更改。最終,你將看到如下內容

    NAME      READY     STATUS     RESTARTS   AGE
    redis     1/1       Running    0          13s
    redis     0/1       Completed  0         6m
    redis     1/1       Running    1         6m
    

此時,容器已終止並重新啟動。這是因為 Redis Pod 的 restartPolicy 設定為 Always

  1. 獲取重新啟動容器的 Shell

    kubectl exec -it redis -- /bin/bash
    
  2. 在你的 Shell 中,進入 /data/redis,並驗證 test-file 仍然存在。

    root@redis:/data/redis# cd /data/redis/
    root@redis:/data/redis# ls
    test-file
    
  3. 刪除為此練習建立的 Pod

    kubectl delete pod redis
    

下一步

  • 請參閱 Volume

  • 請參閱 Pod

  • 除了 emptyDir 提供的本地磁碟儲存外,Kubernetes 還支援許多不同的網路附加儲存解決方案,包括 GCE 上的 PD 和 EC2 上的 EBS,這些解決方案更適合關鍵資料,並將處理掛載和解除安裝節點上的裝置等細節。有關更多詳細資訊,請參閱 Volume

最後修改於 2023 年 8 月 24 日下午 6:38 PST:使用 code_sample 簡碼代替 code 簡碼 (e8b136c3b3)