# K8s 初始化容器、临时容器
# 1. 初始化容器
# 1. 1 初始化容器的用途
初始化容器主要是在主应用启动之前,做一些初始化的操作,比如创建文件、修改内核参数、等待依赖程序启动或其他需要在主程序启动之前需要做的工作。
- Init 容器可以包含一些安装过程中应用容器中不存在的实用工具或个性化代码;
- Init 容器可以安全地运行这些工具,避免这些工具导致应用镜像的安全性降低;
- Init 容器可以以 root 身份运行,执行一些高权限命令;
- Init 容器相关操作执行完成以后即退出,不会给业务容器带来安全隐患。
# 1.2 初始化容器和 PostStart 区别
PostStart:依赖主应用的环境,而且并不一定先于 Command 运行。
InitContainer:不依赖主应用的环境,可以有更高的权限和更多的工具,一定会在主应用启动之前完成
# 1.3 初始化容器和普通容器的区别
Init 容器与普通的容器非常像,除了如下几点:
第一个 Init 容器运行成功后才会运行下一个 Init 容器;
所有的 Init 容器运行成功后才会运行主容器;
如果 Pod 的 Init 容器失败,Kubernetes 会不断地重启该 Pod,直到 Init 容器成功为止,但是 Pod 对应的 restartPolicy 值为 Never,Kubernetes 不会重新启动 Pod。
Init 容器不支持 lifecycle、livenessProbe、readinessProbe 和 startupProbe
# 1.4 初始化容器示例
[root@k8s-master01 ~]# cat init.yaml | |
apiVersion: apps/v1 | |
kind: Deployment | |
metadata: | |
labels: | |
app: nginx-deploy | |
name: nginx-deploy | |
spec: | |
replicas: 3 | |
selector: | |
matchLabels: | |
app: nginx-deploy | |
template: | |
metadata: | |
labels: | |
app: nginx-deploy | |
spec: | |
initContainers: # 初始化容器设定 | |
- name: fix-permissions | |
image: busybox | |
command: ["sh","-c","echo hello kubernetes>/usr/share/nginx/html/index.html"] | |
securityContext: | |
privileged: true | |
volumeMounts: | |
- name: share-volume | |
mountPath: /usr/share/nginx/html | |
containers: | |
- image: nginx | |
name: nginx | |
volumeMounts: | |
- name: timezone | |
mountPath: /etc/timezone | |
- name: tz-config | |
mountPath: /usr/share/zoneinfo/Asia/Shanghai | |
- name: tz-config | |
mountPath: /etc/localtime | |
- name: share-volume | |
mountPath: /usr/share/nginx/html | |
volumes: | |
- name: share-volume | |
emptyDir: {} | |
- name: timezone | |
hostPath: | |
path: /etc/timezone | |
type: File | |
- name: tz-config | |
hostPath: | |
path: /usr/share/zoneinfo/Asia/Shanghai | |
type: File | |
[root@k8s-master01 ~]# kubectl create -f init.yaml | |
[root@k8s-master01 ~]# curl 172.16.32.145 | |
hello kubernetes |
# 2. 临时容器
# 2.1 注入临时容器到 Pod
[root@k8s-master01 ~]# kubectl get pods | |
NAME READY STATUS RESTARTS AGE | |
nginx-deploy-7dd6cd4b44-ktw5k 1/1 Running 1 16h | |
nginx-deploy-7dd6cd4b44-mjcgq 1/1 Running 1 (28m ago) 16h | |
nginx-deploy-7dd6cd4b44-wdm6p 1/1 Running 1 (28m ago) 16h | |
#1. 进入容器发现 pod 没有 ps 和 netstat 命令 | |
[root@k8s-master01 ~]# kubectl exec -it nginx-deploy-7dd6cd4b44-ktw5k -- bash | |
root@nginx-deploy-7dd6cd4b44-ktw5k:/# ps aux | |
root@nginx-deploy-7dd6cd4b44-ktw5k:/# netstat -lntp | |
#2. 注入临时容器至该 Pod | |
[root@k8s-master01 ~]# kubectl debug nginx-deploy-7dd6cd4b44-wdm6p -ti --image=registry.cn-hangzhou.aliyuncs.com/old_xu/debug-tools |
# 2.1 注入临时容器到节点
kubectl debug node k8s-node01 -it --image=registry.cn-hangzhou.aliyuncs.com/old_xu/debug-tools |