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.
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.
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.
The sidecar calls localhost:4000 and reaches posts. No Service, no IP needed.
Separate Pods have separate localhosts. They talk over the cluster network, and in practice through a Service name.
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
- Every Pod gets its own IP on the cluster network.
- Pod IPs are temporary: a replacement Pod gets a new one. Use Services, not Pod IPs.
- Containers in one Pod share the IP and talk on
localhost. - Containers in different Pods talk over the cluster network.
- Containers in one Pod must use different ports.
Quick check
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.