kubernetes init containers
Kubernetes Init Containers
It’s sometimes necessary to prepare a container running in a pod. For example, we might want to wait for service is available, want to configure things at runtime, or init some data in a database. In all of these cases, init containers are useful. The init containers are executed in a sequence before our primary or application containers start.
So let’s create an deployment consisting of an init container
# cat init-container.yaml
apiVersion: v1
kind: Pod
metadata:
name: website
spec:
initContainers:
- name: clone-repo
image: alpine/git
command:
- git
- clone
- --progress
- https://github.com/peterj/simple-http-page.git
- /usr/share/nginx/html
volumeMounts:
- name: web
mountPath: "/usr/share/nginx/html"
containers:
- name: nginx
image: nginx
ports:
- name: http
containerPort: 80
volumeMounts:
- name: web
mountPath: "/usr/share/nginx/html"
volumes:
- name: web
emptyDir: {}
Lets create the Pod using below command
# kubectl apply -f init-container. yaml
pod/website created
# kubectl get pods
NAME READY STATUS RESTARTS AGE
test-db-544bd6b575-zb67d 1/1 Running 0 28h
website 0/1 Running 0 49s
The number 0/1 indicates a total of 1 init container, and 0 containers have been completed so far. In case the init container fails, the status changes to Init: Error or Init: CrashLoopBackOff if the container fails repeatedly.
we can also look at the events using the describe command to see what happened
we will notice as soon as Kubernetes schedules the Pod, the first Docker image is pulled alpine/git, and the init container is created and started. Once that's completed the main application container nginx starts.
we can also use the logs command to get the logs from the init container by specifying the container name using the -c flag
# kubectl logs website -c clone-repo
Cloning into '/usr/share/nginx/html'...
remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (8/8), done.
remote: Total 10 (delta 1), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (10/10), done.
Resolving deltas: 100% (1/1), done.
we can use port-forward to forward the local port to port 80 on the container
# kubectl port-forward pod/website 8000:80
Forwarding from 127.0.0.1:8000 -> 80
Forwarding from [::1]:8000 -> 80
we can clean up after we are done
# kubectl delete pod website
pod "website" deleted
Recent Comments
No comments
Leave a Comment
We will be happy to hear what you think about this post