Kubernetes - container communication within a pod

2019-06-17 00:45发布

From the kubernetes docs:

The applications in a pod all use the same network namespace (same IP and port space), and can thus “find” each other and communicate using localhost.

Is it possible to use some container specific names instead of locahost?

For example, with docker-compose up, you use name of the service to communicate. [docs]

So, if my docker-compose.yml file is

version: '2'
services:
  web:
    build: .
    ports:
      - "8000:8000"
  srv:
    build: .
    ports:
      - "3000:3000"

Then I access srv from within web by calling http://srv:3000/, not http://localhost:3000

How can I achieve the same behaviour in kubernetes? Any way to specify what name to use in pods' yaml configuration?

2条回答
仙女界的扛把子
2楼-- · 2019-06-17 01:15

localhost is just a name for the network loopback device (usually 127.0.0.1 for IPv4 and ::1 for IPv6). This is usually specified in your /etc/hosts file.

A pod has its own IP, so each container inside shares that IP. If these containers should be independent (i.e. don't need to be collocated), they should each be in their own pod. Then, you can define a service for each that allows DNS lookups as either "$SERVICENAME" from pods in the same namespace, or "$SERVICENAME.$NAMESPACE" from pods in different namespaces.

查看更多
forever°为你锁心
3楼-- · 2019-06-17 01:23

docker-compose deploys individual containers, linking them together so they know each other's name and IP.

a Pod in Kubernetes is similar, but this is not the purpose of a Pod to hold multiple external services and link them together.

A Pod is for containers that must be running on the same host, and interact among themselves only. The containers communicate internally via localhost.

Most Pods are in fact a single container.

A Pod communicates with the outside using Services. In essence a Pod appears as if it was just one container.

under the hood, a Pod is at least 2 containers: the pause container manages the IP of the Pod, and then your attached container. This allows your container to crash, restart, and be relinked in the Pod without changing IP, allowing to manage container crashes without involving the scheduler, and making sure the Pod stays on a single node during its lifetime, so restart is fast.

If containers we rescheduled each time they crash, they would potentially end up on a different host, routing would have to be updated etc...

查看更多
登录 后发表回答