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: {}
Save the above YAML to init-container.yaml
and create the Pod using kubectl apply -f init-container.yaml
.
If you run kubectl get pods
right after the above command, you should see the status of the init container:
$ kubectl get po
NAME READY STATUS RESTARTS AGE
website 0/1 Init:0/1 0 1s
The number 0/1
indicates a total of 1 init containers, 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.
You can also look at the events using the describe
command to see what happened:
Normal Scheduled 19s default-scheduler Successfully assigned default/website to minikube
Normal Pulling 18s kubelet, minikube Pulling image "alpine/git"
Normal Pulled 17s kubelet, minikube Successfully pulled image "alpine/git"
Normal Created 17s kubelet, minikube Created container clone-repo
Normal Started 16s kubelet, minikube Started container clone-repo
Normal Pulling 15s kubelet, minikube Pulling image "nginx"
Normal Pulled 13s kubelet, minikube Successfully pulled image "nginx"
Normal Created 13s kubelet, minikube Created container nginx
Normal Started 13s kubelet, minikube Started container nginx
You will notice as soon as Kubernetes schedules the Pod, the first Docker image is pulled (alpine/git
), and the init container (clone-repo
) is created and started. Once that's completed (the container cloned the repo) the main application container (nginx
) starts.
Additionally, you 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: 6, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 6 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (6/6), done.
Finally, to actually see the static HTML page can use port-forward
to forward the local port to the 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
You can now use web view or open your browser at http://localhost:8000
to open the static page.
Delete the Pod by running kubectl delete po website
.