Kubernetes 那些事 — Volume

Andy Chen
Andy的技術分享blog
6 min readMar 10, 2020

--

前言

上一篇文章介紹了 ConfigMap 以及 Secrets 以及如何建立,接下來就要介紹如何正確地套用到 Pod 上,想套用到 Pod 上必須要先了解 Volume,廢話不多說馬上開始今天的文章吧!

什麼是 Volume?

Volumes 為 K8s 用來儲存資料的地方,不但能將 container 的資料存下來,同時也能利用掛載(mounting) 的方式提供給其他 Pod 使用,整體來說跟 Docker 的 Volume 很像,但 K8s 的 Volume 多了生命週期、也比 Docker 支援更多不同類型的 Volume 型態。

Volume 類型

講完什麼是 Volume 後接下來講一下 Volume 的類型吧!這裡筆者講幾個比較常用到的 Volume 類型,想了解更多類型的讀者可以參考這個網站

  • emptyDir

當新增一個新的 Pod 的時候,k8s 就會在這個 Pod 新增一個 emptyDir ,讓這個 Pod 內所有的 container 都可以存取這個 emptyDir ,當 Pod 被移除時,該 emptyDir 也會跟著被移除。

所以只要 kubelet 沒有將 Pod 砍掉重建,其內部的 container 即便重啟都可以存放在 emptyDir 的內容。

  • hostPath

在 Pod 物件上,掛載 Node 的資料夾或檔案,簡單來說就是直接把機器上的檔案掛載到 Pod 中。

  • Cloud Storage

使用雲端硬碟的 Volumes ,常見的有 AWS EBS、Google Disk、Microsoft Azure Disk。

  • Network FileSystem(NFS)

利用 NFS 的原理存取同一個網域下的機器中的資料。

  • ConfigMap
  • Secrets

ConfigMap 與 Secrets 掛載

介紹完 Volume 後接下來就要進入重頭戲,終於要把上一篇文章挖的坑填起來了XD,這邊一樣把之前寫好的 Deployment 在進行改寫。

apiVersion: apps/v1
kind: Deployment
metadata:
name: helloworld
spec:
replicas: 2
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
minReadySeconds: 60
revisionHistoryLimit: 10
selector:
matchLabels:
app: frontend
template:
metadata:
labels:
app: frontend
spec:
containers:
- name: helloworld
image: w5151381guy/helloworld
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
resources:
requests:
cpu: 200m
memory: 500Mi
limits:
cpu: 500m
memory: 800Mi
livenessProbe:
httpGet:
path: /
scheme: HTTP
port: 8080
initialDelaySeconds: 3
periodSeconds: 60
successThreshold: 2
failureThreshold: 5
volumeMounts:
- name: helloworld-config
mountPath: /etc/nginx/conf.d
readOnly: true
- name: helloworld-secret
mountPath: /etc/nginx/ssl
volumes:
- name: helloworld-config
configMap:
name: helloworld-config
- name: helloworld-secret
secret:
secretName: helloworld-secret

這邊可以拆成兩個部分來看,首先我們要先在 Pod 內定義好 Volume 型態,由於示範的內容為 ConfigMap 以及 Secrets,因此會在 Volume 內定義建立好的 ConfigMap 以及 Secrets。

  • name

設定此 Volume 的名稱。

  • configMap

設定 Volume 的類型為 ConfigMap。

  • secret

設定 Volume 的類型為 Secret。

現在 Pod 內已經有定義好的 Volume 了,接下來就可以把 Volume 內的檔案傳進去 container 內了,而這邊會用 volumeMounts 的方式代表掛載 Volume 內的檔案。

  • name

要掛載進 container 的 Volume 名稱,這邊的名稱會從 Volume 內抓取,因此必須要設定的跟上面提到的 name 一致,不然會找不到要掛載的 Volume。

  • mountPath

設定要掛載在 container 中的哪個路徑上,假如所設定的路徑資料夾 container 本身沒有建立,則會創一個新的資料夾並把檔案掛載到進去。

  • readOnly

設定該檔案是否只能讀取,預設為 false

更新 Deployment 內容

接下來把範例的 Deployment 利用 replace 的參數更新內容。

一樣可以下 get 參數查看建立起來的 Pod。

這時候可以進入隨便一個 Pod,查看剛剛掛載進去的 ConfigMap 以及 Secrets,也可以藉此了解 ConfigMap 以及 Secrets 是真的會連結到檔案。

小結

今天介紹了 Volume,也終於把 ConfigMap 以及 Secrets 的掛載介紹完了,相信未來如果要存放跟部署面有關的內容應該都會改用 ConfigMap 以及 Secrets 了方便又好管理,接下來要介紹的內容就比較不一樣了,跟 Pod 的寫法比較沒什麼關聯,那我們就下篇文章見嘍~

--

--

Andy Chen
Andy的技術分享blog

嗨嗨我是Andy,用嘴巴工作的工程師😂,喜歡學習不同領域的內容,專長為網頁開發,歡迎大家跟我聊技術~