配置 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 容器在 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>
  ...

下一步

上次修改时间为 2023 年 8 月 24 日下午 6:38 PST:使用 code_sample shortcode 而不是 code shortcode (e8b136c3b3)