Kubernetes Pod 生命周期之初始化容器
初始化容器定义
Init 容器是一种特殊容器,在 Pod 内的应用容器启动之前运行。Init 容器可以包括一些应用镜像中不存在的实用工具和安装脚本,以用来实现启动前检查依赖服务是否正常并生成初步配置文件。
初始化容器执行过程
- 初始化容器在执行过程中必须依次执行,一旦有一个失败,那么该 Pod 将会执行重启策略
- 只有所有的初始化容器全部执行完毕后,主容器才会开始启动
初始化容器应用
在初始化容器中我生成index.html
给我的应用主容器 nignx
使用,yaml文件如下:
apiVersion: v1
kind: Pod
metadata:
name: nginx-init-config
namespace: default
spec:
initContainers:
- name: initial-config
image: docker.io/library/busybox:1.36
imagePullPolicy: IfNotPresent
command:
- sh
- -c
- echo "<!DOCTYPE html><html><head><title>My Index Page</title></head><body><h1>Welcome to My Index Page</h1><p>This is a sample index.html file.</p></body></html>" > /config-dir/index.html
volumeMounts:
- name: config-dir
mountPath: /config-dir
- name: check-config
image: docker.io/library/busybox:1.36
imagePullPolicy: IfNotPresent
command:
- cat
- "/config-dir/index.html"
volumeMounts:
- name: config-dir
mountPath: /config-dir
containers:
- name: nginx
image: docker.io/library/k8s-test:v1.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
volumeMounts:
- name: config-dir
mountPath: /usr/share/nginx/html
volumes:
- name: config-dir
emptyDir: {}
运行结果如下:
root@k8s-master1:~# kubectl get pods -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx-init-config 1/1 Running 0 29s 10.244.194.104 k8s-worker1 <none> <none>
root@k8s-master1:~# curl http://10.244.194.104
<!DOCTYPE html><html><head><title>My Index Page</title></head><body><h1>Welcome to My Index Page</h1><p>This is a sample index.html file.</p></body></html>
初始化容器日志查看
root@k8s-master1:~# kubectl logs nginx-init-config -c check-config
<!DOCTYPE html><html><head><title>My Index Page</title></head><body><h1>Welcome to My Index Page</h1><p>This is a sample index.html file.</p></body></html>