It’s sometimes necessary to prepare a container running in a pod. For example, you might want to wait for a service being available, want to configure things at runtime, or init some data in a database. In all of these cases, init containers are useful. Note that Kubernetes will execute all init containers (and they must all exit successfully) before the main container(s) are executed.
So let’s create an deployment consisting of an init container that writes a message into a file at /ic/this
and the main (long-running) container reading out this file, then:
kubectl apply -f https://raw.githubusercontent.com/openshift-evangelists/kbe/main/specs/ic/deploy.yaml
Now we can check the output of the main container:
kubectl get deploy,po
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
deployment.extensions/ic-deploy 1 1 1 1 11m
NAME READY STATUS RESTARTS AGE
pod/ic-deploy-bf75cbf87-8zmrb 1/1 Running 0 59s
kubectl logs ic-deploy-bf75cbf87-8zmrb -f
INIT_DONE
INIT_DONE
INIT_DONE
INIT_DONE
INIT_DONE
Send a break signal (Ctrl-C) when you’re ready to disconnect from the log stream:
^C
Now we can cleanup after we are done as follows:
kubectl delete -f https://raw.githubusercontent.com/openshift-evangelists/kbe/main/specs/ic/deploy.yaml
If you want to learn more about init containers and related topics, check out the blog post Kubernetes: A Pod’s Life.