k8s☞04Pod-init容器 - 容器 - k8s - pod

阅读量: zyh 2020-08-26 21:19:04
Categories: > Tags:

使用场景

例子

等待其他服务就绪的例子

apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  initContainers:
  - name: init-myservice
    image: busybox:1.28
    command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"]
  - name: init-mydb
    image: busybox:1.28
    command: ['sh', '-c', "until nslookup mydb.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for mydb; sleep 2; done"]
  containers:
  - name: myapp-container
    image: busybox:1.28
    command: ['sh', '-c', 'echo The app is running! && sleep 3600']

通过添加init容器(init-myservice和init-mydb),等待svc对象创建,延迟启动应用容器(myapp-container)。

需要对服务进行预处理的例子

apiVersion: v1
kind: Pod
metadata:
  name: init-demo
spec:
  volumes:
  - name: workdir
    emptyDir: {}
  initContainers:
  - name: install
    image: busybox
    command:
    - wget
    - "-O"
    - "/work-dir/index.html"
    - http://www.baidu.com  # https
    volumeMounts:
    - name: workdir
      mountPath: "/work-dir"
  containers:
  - name: web
    image: nginx
    ports:
    - containerPort: 80
    volumeMounts:
    - name: workdir
      mountPath: /usr/share/nginx/html

这个例子,通过init容器(install)来提前拉取代码到 workdir 本地临时卷,然后再将 workdir 本地临时卷挂载到 nginx 容器的 /usr/share/nginx/html。

启动顺序

init容器按照Pod.spec.initContainers中定义的顺序启动。