?假設有如下三個節點的 K8S 集群:
k8s31master 是控制節點
k8s31node1、k8s31node2?是工作節點
容器運行時是 containerd
一、理論介紹
1.1、Volumes 卷
Kubernetes 的卷是 pod 的?個組成部分,因此像容器?樣在 pod 的規范(pod.spec)中就定義了。它們不是獨立的 Kubernetes 對象,也不能單獨創建或刪除。pod 中的所有容器都可以使用卷,但必須先將它掛載在每個需要訪問它的容器中。在每個容器中,都可以在其文件系統的任意位置掛載卷。
通過上面的描述,我們知道了使用卷的兩個步驟:
- 在?.spec.volumes 字段中設置為 Pod 提供的卷。
- 在?.spec.containers[*].volumeMounts 字段中聲明卷在容器中的掛載位置。
1.2、為什么需要??
總結:
- 數據持久性。容器的文件在磁盤上是臨時存放的,當容器崩潰重啟或被刪除時,數據也會隨之丟失。
- 共享存儲。多個容器之間共享文件數據。
1.3、常用卷類型
emptyDir、hostPath、nfs、persistentVolumeClaim、configMap、secret。
kubectl explain pod.spec.volumes
二、emptyDir 卷類型
- emptyDir 類型的 Volumes 是在 Pod 被指派到某節點時被創建。
- 就像其名稱所表示的那樣,emptyDir 卷最初是空的。
- Kubernetes 會在節點上自動分配一個目錄,因此無需指定節點上對應的目錄文件。
- 當 Pod 因為某些原因被從節點上刪除時,emptyDir 卷中的數據也會被永久刪除。
2.1、實踐
定義一個 Pod,里面有兩個容器:一個 nginx,一個?alpine。
alpine 每隔3秒往容器目錄 /data 生成一個 index.html。
nginx 讀取這個?index.html 作為首頁。
apiVersion: v1
kind: Pod
metadata:name: emptydir-pod
spec:volumes:- name: sharediremptyDir: {}containers:- name: html-generatorimage: alpine:latest imagePullPolicy: IfNotPresentcommand: ["/bin/sh", "-c", "while true; do echo \"您好,現在時間是 $(date)\" > /data/index.html; sleep 3; done"]volumeMounts:- name: sharedirmountPath: /data- name: nginximage: nginx:1.14.2imagePullPolicy: IfNotPresentvolumeMounts:- name: sharedirmountPath: /usr/share/nginx/htmlreadOnly: trueports:- containerPort: 80protocol: TCP
- emptyDir: {} 表示這是一個空卷。
- command: ["/bin/sh", "-c", "while true; do echo \"您好,現在時間是 $(date)\" > /data/index.html; sleep 3; done"] 表示容器啟動的時候執行命令,該命令每隔3秒往 /data/index.html 打印當前系統時間。
- date:這是一個用于顯示或設置系統日期和時間的命令。當不帶任何參數使用時,它會顯示當前的日期和時間。
- $(command):這是命令替換的語法,在 Shell 中用來獲取命令執行的結果。這里的command 是指任何有效的命令。在本例中,就是 date 命令。Shell 會先運行括號內的命令,并將輸出結果替換掉這個整個表達式。
- 容器?html-generator 和容器?nginx 都掛載了相同的卷?sharedir。
- 每隔3秒請求 Pod IP
?Pod IP 是 10.244.9.1 ; Pod 被調度到 node2。
2.2、查看本機臨時目錄
- 查看 pod 的 uid
kubectl get pod emptydir-pod -oyaml | grep uid
- 進入 node2 /var/lib/kubelet/pod-uid/volumes 下