Create a Pod that runs two Containers
Create a Pod that runs two Containers. The two containers share a Volume that they can use to communicate. Here is the configuration file for the Pod:
pods/two-container-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: two-containers
spec:
restartPolicy: Never
volumes:
- name: shared-data
emptyDir: {}
containers:
- name: nginx-container
image: nginx
volumeMounts:
- name: shared-data
mountPath: /usr/share/nginx/html
- name: debian-container
image: debian
volumeMounts:
- name: shared-data
mountPath: /pod-data
command: ["/bin/sh"]
args: ["-c", "echo Hello from the debian container > /pod-data/index.html"]
-
In the configuration file, you can see that the Pod has a Volume named shared-data.
-
The first container listed in the configuration file runs an nginx server.
-
The mount path for the shared Volume is /usr/share/nginx/html.
-
The second container is based on the debian image, and has a mount path of /pod-data.
-
The second container runs the following command and then terminates.
echo Hello from the debian container > /pod-data/index.html
kubectl apply -f https://k8s.io/examples/pods/two-container-pod.yaml
kubectl get pod two-containers --output=yaml
apiVersion: v1
kind: Pod
metadata:
...
name: two-containers
namespace: default
...
spec:
...
containerStatuses:
- containerID: docker://c1d8abd1 ...
image: debian
...
lastState:
terminated:
...
name: debian-container
...
- containerID: docker://96c1ff2c5bb ...
image: nginx
...
name: nginx-container
...
state:
running:
...
-
You can see that the debian Container has terminated, and the nginx Container is still running.
-
Get a shell to nginx Container:
kubectl exec -it two-containers -c nginx-container -- /bin/bash
root@two-containers:/# apt-get update
root@two-containers:/# apt-get install curl procps
root@two-containers:/# ps aux
USER PID ... STAT START TIME COMMAND
root 1 ... Ss 21:12 0:00 nginx: master process nginx -g daemon off;
root@two-containers:/# curl localhost
Hello from the debian container
The Volume in this example provides a way for Containers to communicate during the life of the Pod. If the Pod is deleted and recreated, any data stored in the shared Volume is lost.