概念:

初始化容器的概念 比如一个容器A依赖其他容器,可以为A设置多个 依赖容易A1,A2,A3

A1,A2,A3要按照顺序启动,A1没有启动启动起来的 话,A2,A3是不会启动的,直到所有的静态容器全 部启动完毕,主容器A才会启动。

一般用于A容器运行之前,先做一些准备工作。
如果初始化容器失败,则会一直重启,pod不会创建


实战:

yaml1

apiVersion: v1
kind: Pod
metadata:
  name: init-pod
  labels:
    app: init-pod
spec:
  containers:
  - name: init-pod
    image: busybox
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
    volumeMounts:
    - mountPath: /xx
      name: workdir
  initContainers:
  - name: init-mkdir
    image: busybox
    command: ['sh', '-c', "touch /work-dir/1112233"]
    volumeMounts:
    - mountPath: /work-dir
      name: workdir
  volumes:
  - name: workdir
    emptyDir: {}

容器成功启动
K8s实战-init容器-LMLPHP


yaml2

apiVersion: v1
kind: Pod
metadata:
  name: init-pod
  labels:
    app: init-pod
spec:
  containers:
  - name: init-pod
    image: busybox
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
    volumeMounts:
    - mountPath: /xx
      name: workdir
  initContainers:
  - name: init-mkdir
    image: busybox
    command: ['sh', '-c', "touch /work-dir/1112233 && sleep 3600"]
    volumeMounts:
    - mountPath: /work-dir
      name: workdir
  volumes:
  - name: workdir
    emptyDir: {}

在初始化容器里面加了sleep后,容器无法正常启动,一直是初始化状态
K8s实战-init容器-LMLPHP

yaml3

apiVersion: v1
kind: Pod
metadata:
  name: init-pod
  labels:
    app: init-pod
spec:
  containers:
  - name: init-pod
    image: busybox
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']
    volumeMounts:
    - mountPath: /xx
      name: workdir
  initContainers:
  - name: init-mkdir
    image: busybox
    command: ['sh', '-c', "touch1 /work-dir/1112233 && sleep 3600"]
    volumeMounts:
    - mountPath: /work-dir
      name: workdir
  volumes:
  - name: workdir
    emptyDir: {}

这里把command里面的touch故意改成touch1,这样会报错,测试如下所示:
K8s实战-init容器-LMLPHP

12-29 03:30