Chapter 6 of 47 · Pods in depth, part 2

Pod networking: IPs, localhost and ports

Every Pod gets its own IP address. That IP is temporary, and every container in the Pod shares it. Those three facts explain most Pod networking surprises.

Every Pod gets an IP

When Kubernetes creates a Pod, it gives the Pod its own IP address on the cluster network. Pods can reach each other directly on these IPs, even across machines.

Two Pods with their own IPs talk over the cluster networkposts-podposts :4000IP 10.244.1.15users-podusers :5000IP 10.244.1.16cluster networkposts can call http://10.244.1.16:5000, and users can call http://10.244.1.15:4000

Pod IPs are temporary

Write down the IP of a Pod below, then crash it and compare:

The replacement is a new Pod with a new name and, almost always, a new IP. Anything that had the old IP hard-coded now points at nothing.

Never design your application around a Pod's IP address. That is one reason Services exist: the Service gives a stable name and IP, and forwards to whichever Pods are alive.
Client  →  posts-service (stable)  →  Pod (comes and goes)

Same Pod: localhost

Containers in the same Pod share one network namespace: one IP, one set of ports, one localhost. Containers in different Pods do not.

Sidecar reaches posts on localhostPod · IP 10.244.1.15postslistens :4000sidecarcurl http://localhost:4000 ✓

The sidecar calls localhost:4000 and reaches posts. No Service, no IP needed.

Ports must not clash

The flip side of sharing one IP: two containers in the same Pod cannot listen on the same port, just like two programs on your laptop cannot both use port 4000. Change the ports below:

Recap

Quick check

A sidecar in the posts Pod calls http://localhost:4000/health. Does it hit posts in the same Pod, or might it hit another posts Pod?
Show answer

Always the same Pod. localhost never leaves the Pod's network namespace. To spread calls across all posts Pods you would call the Service instead.

Pod networking: common questions

Can containers in the same Pod use the same port?

No. They share one network namespace and IP, so only one container can listen on a given port. The second fails with address already in use.

Should I connect to a Pod by its IP?

No. Pod IPs change when Pods are replaced. Use a Service, which gives a stable name and IP in front of the Pods.