Sub topic 6
One IP, shared localhost: Pod networking
This chapter assumes you can read Pod manifests and know what a container image is. It also assumes you know that a cluster has nodes and that each node runs containers.
The Pod network namespace
Every Pod gets one IP address. All containers in the Pod share a single network namespace. A network namespace is the set of network interfaces, IP addresses, routes, and ports that a process sees. The containers share it, so they have the same IP and the same localhost.
A container can reach a neighbor in the same Pod at localhost:<port>. No Service or DNS name is involved. Containers in different Pods use the Pod IP, usually through a Service.
Try it
This Pod runs nginx plus a second container that calls nginx over localhost every five seconds.
apiVersion: v1
kind: Pod
metadata:
name: net-demo
spec:
containers:
- name: nginx
image: nginx:1.27
ports:
- containerPort: 80
- name: client
image: busybox:1.36
command:
- sh
- -c
- while true; do wget -qO- http://localhost:80 | head -n 4; sleep 5; doneApply it and read the client's logs:
kubectl apply -f net-demo.yaml
kubectl logs net-demo -c clientYou should see the start of the nginx welcome page. The client reached nginx without knowing its IP. If the first log is empty, wait a few seconds. The client may have started before nginx was listening.
Port conflicts
Because the containers share one set of ports, two containers in the same Pod cannot listen on the same port. The second process fails to bind, and that container usually ends up in CrashLoopBackOff. Give each container its own port.
What is shared and what is not
| Shared by all containers in the Pod | Separate per container |
|---|---|
| IP address | Filesystem (unless a volume is shared) |
| Port space and `localhost` | Image and process |
| Hostname | Environment variables |
| Volumes you mount into several containers | Resource requests and limits |
Common mistakes
- Using the Pod IP as a stable address. A replacement Pod gets a new IP. Put a Service in front of Pods that other workloads need to reach.
- Binding to
127.0.0.1and expecting outside access. A server bound only to the loopback address accepts connections from neighbor containers but not from other Pods. Bind to0.0.0.0for outside traffic. - Expecting isolation between containers. A sidecar can reach any port the main container opens on localhost. Treat the Pod as one trust boundary.
Exercise
A Pod has two containers, and both run a web server that listens on port 8080. What happens, and how do you fix it?
Show answer
Both containers share one port space, so the second server cannot bind to 8080 and that container fails, typically ending in CrashLoopBackOff. Change one server's listening port, for example to 8081, so each container uses a different port. Other containers in the Pod then reach each server at localhost:8080 and localhost:8081.