建立 Kubernetes 磁碟區

本文說明如何在 Google Kubernetes Engine (GKE) 叢集中建立 Volume 資源。

在 Kubernetes 叢集中,您可以建立 Kubernetes Volume,並在 Deployment 中設定這些 Volume,藉此管理容器化應用程式儲存及共用資料的方式。建立 Kubernetes Volume 後,您就能部署具狀態的微服務。此外,您也能一致地管理應用程式資料,進而加快開發速度。

本文適用於管理 GKE 容器儲存空間的開發人員和管理員。如要進一步瞭解我們在 Google Cloud 內容中提及的常見角色和範例工作,請參閱「常見的 GKE 使用者角色和工作」。

使用磁碟區搭配部署

您可以建立 Pod 的 Deployment,每個 Pod 包含一或多個 Volume。下列 Deployment 資訊清單說明瞭三個 Pod 的 Deployment,每個 Pod 都有一個 emptyDir 磁碟區。詳情請參閱「建立部署作業」。

在這個例子中:

  • metadata: name 欄位會指定名為 volumes-example-deployment 的部署。
  • Pod 範本規格包含 volumes 欄位,用來說明名為 cache-volume 的 emptyDir 磁碟區。
  • 容器規格包含 volumeMounts: 欄位,用於指定名為 cache-volume 的 Volume 會掛接在 /cache 路徑。
  • 資訊清單檔案名稱為 volumes-demo.yaml。
apiVersion: apps/v1
kind: Deployment
metadata:
 name: volumes-example-deployment
spec:
 replicas: 3
 selector:
  matchLabels:
   app: demo
 template:
  metadata:
   labels:
    app: demo
  spec:
   containers:
   - name: test-container
    image: us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0
    volumeMounts:
    - mountPath: /cache
     name: cache-volume
   volumes:
    - name: cache-volume
     emptyDir: {}

如要從這個資訊清單檔案建立部署,請執行以下指令:

kubectl apply -f volumes-demo.yaml

使用以下指令,確認您的部署正確運作並擁有預期的磁碟區:

kubectl describe pods volumes-example-deployment

這會列印出部署中三個 Pod 的個別資訊。輸出結果顯示每個 Pod 都有一個掛接 /cache 的容器 (測試容器):

Mounts:
  /cache from cache-volume (rw)

輸出結果也顯示每個 Pod 都包含一個名為 cache-volume 的磁碟區:

Volumes:
  cache-volume:
    Type:    EmptyDir (a temporary directory that shares a pod's lifetime)

後續步驟