Init containers are a special type of container in K8's that run before the main (regular) application containers start inside a pod. They are used for initialisation or setup tasks that need to happen once before the main app runs.
You can think of them as setup jobs that prepare the environment for the main container:
- Runs to completion before any app containers start.
- Runs sequentially — each one must finish successfully before the next starts.
- Is defined inside a Pod’s spec (just like regular containers).
There are some applications that need to be deployed on Kubernetes cluster and these apps have some pre-requisites where some configurations need to be changed before deploying the app container. Some of these changes cannot be made inside the images so the DevOps team has come up with a solution to use init containers to perform these tasks during deployment.
- Create a
Deploymentnamed asic-deploy-devops. - Configure
specas replicas should be1, labelsappshould beic-devops, template's metadata lablesappshould be the sameic-devops. - The
initContainersshould be named asic-msg-devops, use imagefedorawithlatesttag and use command'/bin/bash','-c'and'echo Init Done - Welcome to xFusionCorp Industries > /ic/blog'. The volume mount should be named asic-volume-devopsand mount path should be/ic. - Main container should be named as
ic-main-devops, use imagefedorawithlatesttag and use command'/bin/bash','-c'and'while true; do cat /ic/blog; sleep 5; done'. The volume mount should be named asic-volume-devopsand mount path should be/ic. - Volume to be named as
ic-volume-devopsand it should be an emptyDir type.
Create the ic-deploy-devops.yaml file.
apiVersion: apps/v1
kind: Deployment
metadata:
name: ic-deploy-devops
spec:
replicas: 1
selector:
matchLabels:
app: ic-devops
template:
metadata:
labels:
app: ic-devops
spec:
initContainers:
- name: ic-msg-devops
image: fedora:latest
command: ["/bin/bash", "-c", "echo Init Done - Welcome to xFusionCorp Industries > /ic/blog"]
volumeMounts:
- name: ic-volume-devops
mountPath: /ic
containers:
- name: ic-main-devops
image: fedora:latest
command: ["/bin/bash", "-c", "while true; do cat /ic/blog; sleep 5; done"]
volumeMounts:
- name: ic-volume-devops
mountPath: /ic
volumes:
- name: ic-volume-devops
emptyDir: {}
Deploy: kubectl apply -f ic-deploy-devops.yaml
Verify its running: kubectl get pods