EmptyDir 的定位#
EmptyDir 可以理解為 Pod 執行期間使用的「臨時目錄」,概念類似於 Docker 中常見的 Volume,但它與 Pod 生命週期共生共滅 — Pod 被移除時,EmptyDir 也會一併刪除。
常見使用情境:
- 同一個 Pod 中多個容器之間共享檔案。
- 作為容器的暫存資料區,用來放快取或中介產物。
主要欄位#
EmptyDir 定義在 .spec.volumes.emptyDir 巢狀欄位中,可用欄位主要有兩個:
medium:此目錄使用的儲存介質。default(預設):使用節點預設儲存介質。Memory:使用 RAM 上的 tmpfs,受記憶體大小限制,但效能極佳,常用於提供高速快取。
sizeLimit:當前 Volume 的容量限制,預設為 nil(不限制)。當medium設為Memory時建議明確設定此值。
建立含多個容器的 Pod#
下面這個範例宣告了一個 EmptyDir,並讓 nginx 與 alpine 兩個容器同時掛載:
apiVersion: v1
kind: Pod
metadata:
name: emptydir-pod
spec:
volumes:
- name: html
emptyDir: {}
containers:
- name: nginx
image: nginx:latest
volumeMounts:
- name: html
mountPath: /usr/share/nginx/html
- name: alpine
image: alpine
volumeMounts:
- name: html
mountPath: /html
command: ["/bin/sh", "-c"]
args: # 每十秒定時向 /html/index.html 寫入資料
- while true; do
echo $(hostname) $(date) >> /html/index.html;
sleep 10;
done兩個容器掛載到同一個名為 html 的 EmptyDir,分別對應到 /usr/share/nginx/html 與 /html。
部署與檢視#
建立 Pod:
kubectl apply -f emptydir.yaml查看 Pod 細節:
kubectl describe pod/emptydir-pod在輸出中可以看到 nginx 與 alpine 都將 html 這個 EmptyDir 掛載至各自的路徑,並且 Volume 區塊顯示:
Volumes:
html:
Type: EmptyDir (a temporary directory that shares a pod's lifetime)
Medium:
SizeLimit: <unset>驗證共享:透過 Nginx 取得 alpine 寫入的內容#
alpine 每 10 秒會寫入一行紀錄到 /html/index.html,而 nginx 容器掛載相同的 EmptyDir 到網頁根目錄,因此可以直接透過 HTTP 看到內容。
對 Pod 做 port forward:
kubectl port-forward pod/emptydir-pod 8080:80使用 curl 確認:
curl http://localhost:8080回傳內容會持續長出新的時間戳記行,例如:
emptydir-pod Tue Jul 26 09:05:47 UTC 2022
emptydir-pod Tue Jul 26 09:05:57 UTC 2022
emptydir-pod Tue Jul 26 09:06:07 UTC 2022進入容器交叉確認#
可以透過 -c 指定容器名稱,分別進入兩個容器確認檔案內容:
kubectl exec -it pods/emptydir-pod -c nginx -- sh
head -3 /usr/share/nginx/html/index.htmlkubectl exec -it pods/emptydir-pod -c alpine -- sh
head -3 /html/index.html兩邊看到的內容一致,證明同一個 EmptyDir 在兩個容器之間是共享的。
使用 Memory 作為高效能快取#
當需要更高的存取速度時,可以將 EmptyDir 的介質改為記憶體(tmpfs),並指定容量上限。相較於前一份範例只需把 volumes 區塊改為:
spec:
volumes:
- name: html
emptyDir:
medium: Memory # 改用 RAM 上的 tmpfs
sizeLimit: 256Mi # 限制最大容量
# containers 區塊保持不變小結#
EmptyDir 是 Kubernetes Volume 中最簡單、最直觀的類型之一:
- 用法簡單:宣告即用,不需要外部儲存資源。
- 適合情境:Pod 生命週期內的臨時資料、容器間的檔案共享、高速記憶體快取。
接下來會進入更貼近正式環境的 Volume 類型,包含 ConfigMap、Secret、PV 與 PVC。
原文出處#
- GitHub:https://github.com/MikeHsu0618/2022-ithelp/tree/main/Day17
- iThome:https://ithelp.ithome.com.tw/articles/10292404