設定 Pod 初始化
本頁說明如何在應用程式容器執行之前使用 Init 容器初始化 Pod。
準備開始
您需要有一個 Kubernetes 叢集,並且必須將 kubectl 命令列工具設定為與您的叢集通訊。建議在至少有兩個節點且未充當控制平面主機的叢集上執行本教學課程。如果您還沒有叢集,可以使用 minikube 建立一個,或者您可以使用這些 Kubernetes Playground
若要檢查版本,請輸入kubectl version
。建立具有 Init 容器的 Pod
在本練習中,您將建立一個具有一個應用程式容器和一個 Init 容器的 Pod。init 容器會在應用程式容器啟動之前執行完成。
以下是 Pod 的組態檔
apiVersion: v1
kind: Pod
metadata:
name: init-demo
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
volumeMounts:
- name: workdir
mountPath: /usr/share/nginx/html
# These containers are run during pod initialization
initContainers:
- name: install
image: busybox:1.28
command:
- wget
- "-O"
- "/work-dir/index.html"
- http://info.cern.ch
volumeMounts:
- name: workdir
mountPath: "/work-dir"
dnsPolicy: Default
volumes:
- name: workdir
emptyDir: {}
在組態檔中,您可以看到 Pod 有一個 Init 容器和應用程式容器共用的磁碟區。
init 容器將共用磁碟區掛載在 /work-dir
,而應用程式容器將共用磁碟區掛載在 /usr/share/nginx/html
。init 容器執行以下指令,然後終止
wget -O /work-dir/index.html http://info.cern.ch
請注意,init 容器會在 nginx 伺服器的根目錄中寫入 index.html
檔案。
建立 Pod
kubectl apply -f https://k8s.io/examples/pods/init-containers.yaml
驗證 nginx 容器是否正在執行
kubectl get pod init-demo
輸出顯示 nginx 容器正在執行
NAME READY STATUS RESTARTS AGE
init-demo 1/1 Running 0 1m
取得 init-demo Pod 中執行之 nginx 容器的 Shell
kubectl exec -it init-demo -- /bin/bash
在您的 Shell 中,將 GET 請求傳送到 nginx 伺服器
root@nginx:~# apt-get update
root@nginx:~# apt-get install curl
root@nginx:~# curl localhost
輸出顯示 nginx 正在提供由 init 容器寫入的網頁
<html><head></head><body><header>
<title>http://info.cern.ch</title>
</header>
<h1>http://info.cern.ch - home of the first website</h1>
...
<li><a href="http://info.cern.ch/hypertext/WWW/TheProject.html">Browse the first website</a></li>
...
下一步
- 進一步瞭解在同一個 Pod 中執行的 Container 之間進行通訊。
- 進一步瞭解初始化容器。
- 進一步瞭解Volume。
- 進一步瞭解除錯初始化容器
上次修改時間 2023 年 8 月 24 日下午 6:38 PST:使用 code_sample shortcode 取代 code shortcode (e8b136c3b3)