Container and Kubernetes load balancing
medium 30 minContainers come and go and their addresses change.
See it run
Pods change, the Service stays: four ways in, pods that die and return, how one pod is chosen, and how to stop one without losing a request.
Operations
Four ways in
ClusterIP, NodePort, LoadBalancer and a gateway, each built on the one before.
Step 1 of 4
ClusterIP
Inside only
Only pods inside can call it. The address is virtual: no machine owns it.
Step 1: ClusterIP
kind: Servicespec: type: ClusterIP # inside only # type: NodePort # 30000-32767 on each node # type: LoadBalancer # asks the cloud---kind: HTTPRoute # rules by host and path- Decides per
- Connection
- Costs
- Kernel rules
- Gateway
- per request
Choose the smallest one that works. Most Services in a cluster are ClusterIP.
In the real world
The same container and kubernetes load balancing doing real jobs. Pick one and step through it.
A tenth of the traffic for the new version.
Step 1 of 3
By counting pods
1% would need 99 old pods
Nine old pods and one new pod share one Service: 10%.
Step 1: By counting pods
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Labels that do not match
criticalThe list stays empty and every call fails, though all pods run.
Wrongselector: { app: shop }labels: { app: shop-web }Rightselector: { app: shop }labels: { app: shop }Exiting at once on stop
majorOther nodes still send connections for a moment.
Wrongon SIGTERM: exit(0)RightpreStop: sleep 10on SIGTERM: finish requests, then exitTesting the database in liveness
criticalA slow database restarts all pods together and makes it worse.
Wrongliveness: GET /health # asks the databaseRightliveness: GET /alive # only this processreadiness: GET /readyExpecting balanced gRPC from a Service
majorThe choice is made once per connection.
Wrongchannel = connect("orders:50051")Rightchannel = connect("dns:///orders-headless:50051", policy="round_robin")
Interview tips
How to explain it
- Pods change, the Service stays.
- Labels select, readiness admits.
- Kernel rules pick a pod per connection.
Memory trick: CLIP
- ClusterIP, LoadBalancer.
- Ingress (not a type), Port of a node.
- Readiness removes, liveness restarts.
Choose
- Inside: ClusterIP.
- Web from outside: Gateway.
- Other protocols: LoadBalancer.
- Client picks: headless.
Check before release
- Readiness says the truth.
- Pause and grace period.
- Long connections.
- Ingress NGINX is retired.