Before containers running applications are started, one or some init containers are started first. If there are multiple init containers, they will be started in the defined sequence. The application containers are started only after all init containers run to completion and exit. Storage volumes in a pod are shared. Therefore, the data generated in the init containers can be used by the application containers.
Init containers can be used in multiple Kubernetes resources, such as Deployments, DaemonSets, and jobs. They perform initialization before application containers are started.
Before deploying a service, you can use an init container to make preparations before the pod where the service is running is deployed. After the preparations are complete, the init container runs to completion and exit, and the container to be deployed will be started.
For details, see Init Containers.
vi deployment.yaml
An example YAML file is provided as follows:
apiVersion: apps/v1 kind: Deployment metadata: name: mysql spec: replicas: 1 selector: matchLabels: name: mysql template: metadata: labels: name: mysql spec: initContainers: - name: getresource image: busybox command: ['sleep 20'] containers: - name: mysql image: percona:5.7.22 imagePullPolicy: Always ports: - containerPort: 3306 resources: limits: memory: "500Mi" cpu: "500m" requests: memory: "500Mi" cpu: "250m" env: - name: MYSQL_ROOT_PASSWORD value: "mysql"
kubectl create -f deployment.yaml
Information similar to the following is displayed:
deployment.apps/mysql created
docker ps -a|grep mysql
The init container will exit after it runs to completion. The query result Exited (0) shows the exit status of the init container.