Configure Pod Initialization

This page shows how to use an Init Container to initialize a Pod before an application Container runs.

Before you begin

You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:

To check the version, enter kubectl version.

Create a Pod that has an Init Container

In this exercise you create a Pod that has one application Container and one Init Container. The init container runs to completion before the application container starts.

Here is the configuration file for the Pod:

pods/init-containers.yamlConfigure Pod Initialization - 图1

  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: init-demo
  5. spec:
  6. containers:
  7. - name: nginx
  8. image: nginx
  9. ports:
  10. - containerPort: 80
  11. volumeMounts:
  12. - name: workdir
  13. mountPath: /usr/share/nginx/html
  14. # These containers are run during pod initialization
  15. initContainers:
  16. - name: install
  17. image: busybox:1.28
  18. command:
  19. - wget
  20. - "-O"
  21. - "/work-dir/index.html"
  22. - http://info.cern.ch
  23. volumeMounts:
  24. - name: workdir
  25. mountPath: "/work-dir"
  26. dnsPolicy: Default
  27. volumes:
  28. - name: workdir
  29. emptyDir: {}

In the configuration file, you can see that the Pod has a Volume that the init container and the application container share.

The init container mounts the shared Volume at /work-dir, and the application container mounts the shared Volume at /usr/share/nginx/html. The init container runs the following command and then terminates:

  1. wget -O /work-dir/index.html http://info.cern.ch

Notice that the init container writes the index.html file in the root directory of the nginx server.

Create the Pod:

  1. kubectl apply -f https://k8s.io/examples/pods/init-containers.yaml

Verify that the nginx container is running:

  1. kubectl get pod init-demo

The output shows that the nginx container is running:

  1. NAME READY STATUS RESTARTS AGE
  2. init-demo 1/1 Running 0 1m

Get a shell into the nginx container running in the init-demo Pod:

  1. kubectl exec -it init-demo -- /bin/bash

In your shell, send a GET request to the nginx server:

  1. root@nginx:~# apt-get update
  2. root@nginx:~# apt-get install curl
  3. root@nginx:~# curl localhost

The output shows that nginx is serving the web page that was written by the init container:

  1. <html><head></head><body><header>
  2. <title>http://info.cern.ch</title>
  3. </header>
  4. <h1>http://info.cern.ch - home of the first website</h1>
  5. ...
  6. <li><a href="http://info.cern.ch/hypertext/WWW/TheProject.html">Browse the first website</a></li>
  7. ...

What’s next