k8s学习(6):init容器

概念

init容器有如下几个特点:

  • init容器总是运行到成功完成为止
  • 每个init容器都必须在下一个init容器启动之前成功完成
  • 如果Pod的init容器失败,kubernetes会不断重启该pod,直到init容器成功为止。如果Pod对应的restartPolicy为Never,他不会重新启动。

image-20200130124724935

实例

init模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: busybox
command: ['sh', '-c', 'echo The app is running! && sleep 3600']
initContainers:
- name: init-myservice
image: busybox
command: ['sh', '-c', 'until nslookup myservice; do echo waiting for myservice; sleep 2; done;']
- name: init-mydb
image: busybox
command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep2; done']

查看pod创建详情

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 这时候查看pod状态
kubectl get pod
NAME READY STATUS RESTARTS AGE
myapp-pod 0/1 Init:0/2 0 3m42s

# 查看pod详情,可以看到创建pod成功,但是并没有继续执行下一步,原因是init容器命令并未执行成功
kubectl describe pod myapp-pod
Name: myapp-pod
Namespace: default
Priority: 0
Node: k8s-node01/192.168.128.141
Start Time: Thu, 30 Jan 2020 15:51:03 +0800
Labels: app=myapp
Annotations: <none>
Status: Pending
IP: 10.244.1.6
...
中间省略
...
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 59s default-scheduler Successfully assigned default/myapp-pod to k8s-node01
Normal Pulling 57s kubelet, k8s-node01 Pulling image "busybox"
Normal Pulled 45s kubelet, k8s-node01 Successfully pulled image "busybox"
Normal Created 45s kubelet, k8s-node01 Created container init-myservice
Normal Started 44s kubelet, k8s-node01 Started container init-myservice


# 查看pod日志,可以看到nslookup执行不通过
kubectl log myapp-pod -c init-myservice
log is DEPRECATED and will be removed in a future version. Use logs instead.
Server: 10.96.0.10
Address: 10.96.0.10:53

** server can't find myservice.default.svc.cluster.local: NXDOMAIN

*** Can't find myservice.svc.cluster.local: No answer
*** Can't find myservice.cluster.local: No answer
*** Can't find myservice.default.svc.cluster.local: No answer
*** Can't find myservice.svc.cluster.local: No answer
*** Can't find myservice.cluster.local: No answer


这时候需要创建一个svc,使得init容器可以nslookup执行成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
apiVersion: v1
kind: Service
metadata:
name: myservice
spec:
ports:
- protocol: TCP
port: 80
targetPort: 9376
---
apiVersion: v1
kind: Service
metadata:
name: mydb
spec:
ports:
- protocol: TCP
port: 80
targetPort: 9377

特殊说明

image-20200130161407116

image-20200130161726618