ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

K8s实战-init容器

2026/9/12 12:28:52 拓冰建站 浏览量
K8s实战-init容器

概念:

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

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

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


实战:

yaml1

apiVersion: v1
kind: Pod
metadata:name: init-podlabels:app: init-pod
spec:containers:- name: init-podimage: busyboxcommand: ['sh', '-c', 'echo The app is running! && sleep 3600']volumeMounts:- mountPath: /xxname: workdirinitContainers:- name: init-mkdirimage: busyboxcommand: ['sh', '-c', "touch /work-dir/1112233"]volumeMounts:- mountPath: /work-dirname: workdirvolumes:- name: workdiremptyDir: {}

容器成功启动
在这里插入图片描述


yaml2

apiVersion: v1
kind: Pod
metadata:name: init-podlabels:app: init-pod
spec:containers:- name: init-podimage: busyboxcommand: ['sh', '-c', 'echo The app is running! && sleep 3600']volumeMounts:- mountPath: /xxname: workdirinitContainers:- name: init-mkdirimage: busyboxcommand: ['sh', '-c', "touch /work-dir/1112233 && sleep 3600"]volumeMounts:- mountPath: /work-dirname: workdirvolumes:- name: workdiremptyDir: {}

在初始化容器里面加了sleep后,容器无法正常启动,一直是初始化状态
在这里插入图片描述

yaml3

apiVersion: v1
kind: Pod
metadata:name: init-podlabels:app: init-pod
spec:containers:- name: init-podimage: busyboxcommand: ['sh', '-c', 'echo The app is running! && sleep 3600']volumeMounts:- mountPath: /xxname: workdirinitContainers:- name: init-mkdirimage: busyboxcommand: ['sh', '-c', "touch1 /work-dir/1112233 && sleep 3600"]volumeMounts:- mountPath: /work-dirname: workdirvolumes:- name: workdiremptyDir: {}

这里把command里面的touch故意改成touch1,这样会报错,测试如下所示:
在这里插入图片描述