k8s初級實戰05--pod & container
阿新 • • 發佈:2020-12-30
技術標籤:K8S & DockerpodcontainerinitContainerKubernetes
k8s初級實戰05--配置container & pod
1 基礎概念
Pod 是一組緊密關聯的容器集合,它們共享 IPC 和 Network namespace,是 Kubernetes 排程的基本單位。Pod 的設計理念是支援多個容器在一個 Pod 中共享網路和檔案系統,可以通過程序間通訊和檔案共享這種簡單高效的方式組合完成服務。
k8s 中既可以部署單容器的pod,也可以部署多容器的pod。
pod 中既可以包括一個容器,也可以包括多個容器;容器既可以全部是業務容器,也可以包括Init容器。
2 常見用法
- 建立pod
vim pod_web_single.yaml kind: Pod apiVersion: v1 metadata: name: web-sg spec: containers: - name: web-sg image: nginx:1.19.6 $ kubectl apply -f pod_web_single.yaml pod/web-sg created
- 檢視pod
$ kubectl get po [|
- 刪除pod
$ kubectl delete pod web-sg pod "web-sg" deleted 或者 $ kubectl delete -f pod_web_single.yaml pod "web-sg" deleted
- 建立多容器pod
vim pod_web_double.yaml kind: Pod apiVersion: v1 metadata: name: web-db spec: containers: - name: web-nginx image: nginx:1.19.6 - name: busybox image: busybox:1.32 command: [sh,-c,'sleep 100'] $ kubectl apply -f pod_web_double.yaml pod/web-db created $ kubectl get po|grep web-db web-db 2/2 Running 0 87s 由於該pod有2個容器,因此ready狀態為2/2
- 建立多容器pod共享儲存
此處建立2個容器的pod,掛載同一個卷,進入busybox中新建busybox後,可以在ngixn中發現該目錄也有同樣的檔案,即同一個pod內可以通過掛載卷實現檔案共享。vim pod_web_sharefile.yaml kind: Pod apiVersion: v1 metadata: name: web-sharefile spec: containers: - name: web-nginx image: nginx:1.19.6 volumeMounts: - mountPath: /data name: data - name: busybox image: busybox:1.32 command: [sh,-c,'sleep 1000'] volumeMounts: - mountPath: /data name: data volumes: - name: data emptyDir: {} $ kubectl apply -f pod_web_sharefile.yaml pod/web-sharefile created 測試檔案共享: $ kubectl exec -it web-sharefile -c busybox -- sh / # cd data/ /data # touch busybox.txt /data # exit $ kubectl exec -it web-sharefile -c web-nginx -- sh # ls /data busybox.txt
- 建立包含init容器的pod
此時進入 web-init 的 nginx 容器中,curl 127.0.0.1 發現返回的內容正好是initContainer 寫入的內容,如下圖:vim pod_web_init.yaml kind: Pod apiVersion: v1 metadata: name: web-init spec: containers: - name: web-nginx image: nginx:1.19.6 volumeMounts: - mountPath: /usr/share/nginx/html name: data initContainers: - name: busybox image: busybox:1.32 command: [sh,-c,'echo hello initContainers >/usr/share/nginx/html/index.html;sleep 30'] volumeMounts: - mountPath: /usr/share/nginx/html name: data volumes: - name: data emptyDir: {} $ kubectl apply -f pod_web_init.yaml pod/web-init created 建立開始至sleep 30期間,都為Init:0/1 $ kubectl get pod |grep web-init web-init 0/1 Init:0/1 0 15s init容器退出後,才會開始初始化nginx容器,正常啟動後出現Runing狀態 $ kubectl get pod |grep web-init web-init 0/1 Init:0/1 0 34s $ kubectl get pod |grep web-init web-init 0/1 PodInitializing 0 35s $ kubectl get pod |grep web-init web-init 1/1 Running 0 40s
3 注意事項
- 多容器pod一般適用於容器生命週期一致的場景。
- init 容器執行完後需要退出,若init一直為running狀態,則應用容器無法執行。