Published on

Kubernetes init container

Authors
  • avatar
    Name
    Yuchen Wei
    Twitter

About init

  • A Pod can have multiple containers, and the application runs in the container, but it may also have one or more Init containers that are started before the application container.
  • Init containers are very similar to ordinary containers, except for the following two points: Init containers always run until successful completion Each Init container must complete successfully before the next Init container starts
  • If the Init container of a Pod fails, Kubernetes will continue to restart the Pod until the Init container succeeds. However,
  • If the corresponding restartPolicy of the Pod is Never, it will not restart

Init container yaml

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;'] #DNS name is "myservice",if can't parse will retry after 2 seconds)
  - name: init-mydb
    image: busybox
    command: ['sh', '-c', 'until nslookup mydb; do echo waiting for mydb; sleep 2; done;']

Lifecycle about init container

  • During Pod startup, the Init container is started sequentially after network and data volumes are initialized. Each container must exit successfully before the next container can start
  • If the container fails to start due to runtime or failure exit, it will be retried according to the policy specified by the Pod's restartPolicy. However, if the Pod's restartPolicy is set to Always, the Init container will use RestartPolicy policy
  • The Pod will not become Ready until all Init containers have succeeded. The Init container's ports will not be aggregated in the Service. The Pod being initialized is in the Pending state, but the Initializing state should be set to true
  • If the Pod is restarted, all Init containers must be re-executed
  • Modifications to the Init container spec are limited to the container image field, and modifications to other fields will not take effect. Changing the image field of the Init container is equivalent to restarting the Pod