Pods in Kubernetes have their own real IP addresses. Containers within a pod share network namespace, so they see each other as localhost. This is implemented by the network container by default, which acts as a bridge to dispatch traffic for every container in a pod. Let's see how this works in the following example. Let's use the first example from Chapter 3, Getting Started with Kubernetes, which includes two containers, nginx and centos, inside one pod:
#cat 6-1-1_pod.yaml apiVersion: v1 kind: Pod metadata: name: example spec: containers: - name: web image: nginx - name: centos image: centos command: ["/bin/sh", "-c", "while : ;do curl http://localhost:80/; sleep 10; done"]
// create the Pod #kubectl create -f 6-1-1_pod.yaml pod/example created
Then, we will describe the pod and look at its Container ID:
# kubectl describe pods example Name: example Node: minikube/192.168.99.100 ... Containers: web: Container ID: docker:// d9bd923572ab186870284535044e7f3132d5cac11ecb18576078b9c7bae86c73 Image: nginx ... centos: Container ID: docker: //f4c019d289d4b958cd17ecbe9fe22a5ce5952cb380c8ca4f9299e10bf5e94a0f Image: centos ...
In this example, web has the container ID d9bd923572ab, and centos has the container ID f4c019d289d4. If we go into the minikube/192.168.99.100 node using docker ps, we can check how many containers Kubernetes actually launches since we're in minikube, which launches lots of other cluster containers. Check out the latest launch time by using the CREATED column, where we will find that there are three containers that have just been launched:
# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f4c019d289d4 36540f359ca3 "/bin/sh -c 'while : " 2 minutes ago Up 2 minutes k8s_centos_example_default_9843fc27-677b-11e7-9a8c-080027cafd37_1 d9bd923572ab e4e6d42c70b3 "nginx -g 'daemon off" 2 minutes ago Up 2 minutes k8s_web_example_default_9843fc27-677b-11e7-9a8c-080027cafd37_1 4ddd3221cc47 gcr.io/google_containers/pause-amd64:3.0 "/pause" 2 minutes ago Up 2 minutes
There is an additional container, 4ddd3221cc47, that was launched. Before digging into which container it is, let's check the network mode of our web container. We will find that the containers in our example pod are running in containers with a mapped container mode:
# docker inspect d9bd923572ab | grep NetworkMode "NetworkMode": "container:4ddd3221cc4792207ce0a2b3bac5d758a5c7ae321634436fa3e6dd627a31ca76",
The 4ddd3221cc47 container is the so-called network container in this case. This holds the network namespace to let the web and centos containers join. Containers in the same network namespace share the same IP address and network configuration. This is the default implementation in Kubernetes for achieving container-to-container communications, which is mapped to the first requirement.