配置 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 中,向 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 容器 的更多信息。
- 了解有关 卷 的更多信息。
- 了解有关 调试 Init 容器 的更多信息
上次修改时间:2023 年 8 月 24 日 下午 6:38 PST:使用 code_sample 短代码代替 code 短代码 (e8b136c3b3)