Kubernetes 中的 Init 容器是什么?

Init 容器是 Pod 中的特殊容器,它会在其他容器启动之前运行,用于做一些初始化工作。它具有以下特征:

  • Init 容器必须执行完成才会运行其他容器。
  • 每个 Init 容器必须达成成功状态(0),Pod才能达到运行状态。
  • Init 容器会按定义的顺序执行。
  • 如果任何 Init 容器失败,Kubernetes 会重新启动 Pod,直到 Init 容器成功为止。

使用 Init 容器的主要好处是:

  • 解耦:从主容器中解耦出初始化逻辑,使其更加专注。
  • 重用:Init 容器中的逻辑可在不同 Pod 中复用。

Init 容器常见的使用场景有:

  • 提供实用工具:如git、vi等,用于主容器运行前的配置工作。
  • 安装依赖:用于安装主容器运行所需的依赖。
  • 权限配置:用于提升主容器权限以便运行,如安装定制的 RPM。
  • 抢占式资源配置:用于配置网络、存储等与主容器相竞争的资源。

要使用 Init 容器,需要在 Pod spec 中设置 initContainers:

yaml
apiVersion: v1 
kind: Pod
metadata: 
  name: myapp-pod
spec:
  initContainers:
  - name: init-tools
    image: ubuntu
    command: ['sh', '-c', 'apt-get update && apt-get install -y util-linux']
  - name: init-config
    image: busybox
    command: ['sh', '-c', 'echo "hello" > /work-dir/config.txt']
  containers:
  - name: myapp-container
    image: busybox:1.28 
    command: ['sh', '-c', 'echo "Contents of config:" && cat /work-dir/config.txt']
    volumeMounts:
    - name: workdir
      mountPath: /work-dir
  volumes: 
  - name: workdir
    emptyDir: {}

在这个 Pod 中:

  • initContainers 定了两个 Init 容器:
  • init-tools:安装工具。
  • init-config:创建配置文件。
  • 然后是主容器 myapp-container。
  • init-config 将创建的配置文件挂载到空目录卷 workdir。
  • myapp-container 启动时会读取该配置文件。
  • Init 容器运行完成后,myapp-container 才会启动。

所以总结来说,Init 容器具有以下特征:

  1. 在主容器启动前运行,用于初始化工作。
  2. 必须成功完成,Pod 才能运行。
  3. 按定义顺序执行。
  4. 失败会重启 Pod。

它的主要用途是:

  1. 解耦初始化逻辑。
  2. 可重用。

常见场景是:

  1. 安装工具/依赖。
  2. 权限配置。
  3. 抢占式资源配置。