配置 Pod 初始化
此页面介绍如何使用 Init 容器在应用容器运行之前初始化 Pod。
准备工作
你需要拥有一个 Kubernetes 集群,并且 kubectl 命令行工具已经被配置为与你的集群通信。本教程建议在至少有两个非控制平面主机的节点的集群上运行。如果你还没有集群,可以使用 minikube 创建一个,或者使用以下 Kubernetes 操场之一:
要检查版本,输入 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 容器和应用容器共享的 Volume。
Init 容器将共享的 Volume 挂载到 /work-dir
,而应用容器将共享的 Volume 挂载到 /usr/share/nginx/html
。Init 容器运行以下命令,然后终止:
wget -O /work-dir/index.html http://info.cern.ch
请注意,Init 容器将 index.html
文件写入了 nginx 服务器的根目录。
创建 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 中,向 nginx 服务器发送 GET 请求
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 中运行的容器之间的通信。
- 详细了解 Init 容器。
- 详细了解 Volume。
- 详细了解 调试 Init 容器
上次修改时间:2023年8月24日太平洋时间下午6:38:使用 code_sample shortcode 替换 code shortcode (e8b136c3b3)