Services
Pods come and go, and every new Pod gets a new IP. Clients need something stable. A Service gives a set of Pods one fixed virtual IP (the ClusterIP) and DNS name, and load-balances connections across whichever Pods currently match its selector and are Ready.
apiVersion: v1
kind: Service
metadata:
name: web
spec:
type: ClusterIP # the default
selector:
app: web # route to Ready Pods with this label
ports:
- name: http
port: 80 # the port clients use on the Service
targetPort: 8080 # the container port (number or a named port)
protocol: TCPHow traffic finds Pods
- The EndpointSlice controller watches Pods matching the selector and writes their IPs (marking whether each is Ready) into EndpointSlice objects.
- kube-proxy on every node turns the Service IP + EndpointSlices into iptables/IPVS rules (or a CNI like Cilium does it with eBPF).
- A client connects to
10.96.120.15:80; the node's rules rewrite it to one Pod'sIP:8080.
kubectl get svc web
kubectl get endpointslices -l kubernetes.io/service-name=webSample output:
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
web ClusterIP 10.96.120.15 <none> 80/TCP 2m
NAME ADDRESSTYPE PORTS ENDPOINTS AGE
web-x7q2m IPv4 8080 10.244.1.5,10.244.2.7,10.244.2.9 2mHere is the endpoint selection and a round-robin balancer as a model. Only Pods that match the selector and are Ready receive traffic:
from itertools import cycle
pods = [
{"name": "web-1", "ip": "10.244.1.5", "labels": {"app": "web"}, "ready": True},
{"name": "web-2", "ip": "10.244.2.7", "labels": {"app": "web"}, "ready": True},
{"name": "web-3", "ip": "10.244.2.9", "labels": {"app": "web"}, "ready": False},
{"name": "db-0", "ip": "10.244.1.8", "labels": {"app": "db"}, "ready": True},
]
service = {"name": "web", "selector": {"app": "web"}, "port": 80, "targetPort": 8080}
def endpoints(svc, pods):
return [f"{p['ip']}:{svc['targetPort']}" for p in pods
if all(p["labels"].get(k) == v for k, v in svc["selector"].items()) and p["ready"]]
eps = endpoints(service, pods)
print("endpoints:", eps)
rr = cycle(eps)
for request in range(1, 6):
print(f"request {request}: 10.96.120.15:80 -> {next(rr)}")
pods[2]["ready"] = True # web-3's readiness probe starts passing
print("endpoints now:", endpoints(service, pods))endpoints: ['10.244.1.5:8080', '10.244.2.7:8080']
request 1: 10.96.120.15:80 -> 10.244.1.5:8080
request 2: 10.96.120.15:80 -> 10.244.2.7:8080
request 3: 10.96.120.15:80 -> 10.244.1.5:8080
request 4: 10.96.120.15:80 -> 10.244.2.7:8080
request 5: 10.96.120.15:80 -> 10.244.1.5:8080
endpoints now: ['10.244.1.5:8080', '10.244.2.7:8080', '10.244.2.9:8080']
Note: kube-proxy's default iptables mode actually picks a backend randomly per connection (with equal probability), and IPVS mode supports round-robin and other algorithms. Either way the load spreads evenly over many connections. Also, balancing is per connection, not per request: a long-lived HTTP/2 or gRPC connection sticks to one Pod.
Service types
| Type | Reachable from | How |
|---|---|---|
ClusterIP |
Inside the cluster only | Virtual IP from the service CIDR |
NodePort |
Outside, via <any-node-IP>:<nodePort> |
Opens the same port (30000–32767) on every node, then forwards to the ClusterIP |
LoadBalancer |
The internet / your network | Asks the cloud for an external load balancer pointing at the NodePorts |
ExternalName |
Inside | A DNS CNAME to an outside name (db.example.com); no proxying |
Headless (clusterIP: None) |
Inside | No virtual IP: DNS returns the Pod IPs directly |
apiVersion: v1
kind: Service
metadata:
name: web-public
spec:
type: LoadBalancer
selector: {app: web}
ports:
- {port: 80, targetPort: 8080} # nodePort is allocated automaticallyEach type builds on the previous one. A LoadBalancer Service also has a NodePort and a ClusterIP. This model shows the hops for a request:
svc = {"clusterIP": "10.96.40.2", "port": 80, "nodePort": 31080, "lb": "203.0.113.10", "targetPort": 8080}
pod_ip = "10.244.2.7"
paths = {
"ClusterIP (from a Pod)": [f"{svc['clusterIP']}:{svc['port']}", f"{pod_ip}:{svc['targetPort']}"],
"NodePort (from your laptop)": [f"192.168.1.21:{svc['nodePort']}", f"{svc['clusterIP']}:{svc['port']}", f"{pod_ip}:{svc['targetPort']}"],
"LoadBalancer (from the internet)": [f"{svc['lb']}:{svc['port']}", f"192.168.1.21:{svc['nodePort']}", f"{svc['clusterIP']}:{svc['port']}", f"{pod_ip}:{svc['targetPort']}"],
}
for kind, hops in paths.items():
print(f"{kind}:")
print(" " + " -> ".join(hops))ClusterIP (from a Pod):
10.96.40.2:80 -> 10.244.2.7:8080
NodePort (from your laptop):
192.168.1.21:31080 -> 10.96.40.2:80 -> 10.244.2.7:8080
LoadBalancer (from the internet):
203.0.113.10:80 -> 192.168.1.21:31080 -> 10.96.40.2:80 -> 10.244.2.7:8080
(The ClusterIP hop is logical: the node's rules translate straight to the Pod.)
Headless Services
Set clusterIP: None when clients need to reach individual Pods, for example database replicas in a StatefulSet. DNS then answers with every Ready Pod's IP instead of one virtual IP.
apiVersion: v1
kind: Service
metadata:
name: db
spec:
clusterIP: None
selector: {app: db}
ports:
- port: 5432Session affinity and traffic policies
sessionAffinity: ClientIPsends the same client IP to the same Pod (for ~3 hours by default).externalTrafficPolicy: Local(NodePort/LoadBalancer) only sends to Pods on the receiving node, preserving the client's source IP and avoiding a second hop, at the cost of uneven balance.internalTrafficPolicy: Localdoes the same for in-cluster traffic.
import zlib
backends = ["10.244.1.5", "10.244.2.7", "10.244.2.9"]
def pick(client_ip):
# stable choice per client, like ClientIP affinity
return backends[zlib.crc32(client_ip.encode()) % len(backends)]
for client in ["172.16.0.4", "172.16.0.9", "172.16.0.4", "172.16.0.20", "172.16.0.9"]:
print(client, "->", pick(client))172.16.0.4 -> 10.244.1.5
172.16.0.9 -> 10.244.2.7
172.16.0.4 -> 10.244.1.5
172.16.0.20 -> 10.244.2.9
172.16.0.9 -> 10.244.2.7
Debugging a Service
The classic problem is a Service with no endpoints: the selector doesn't match the Pod labels, or the Pods aren't Ready.
kubectl describe svc web | grep -i endpoints
kubectl get pods -l app=web --show-labels
kubectl port-forward svc/web 8080:80
kubectl run tmp --rm -it --image=busybox:1.37 -- wget -qO- http://webTest yourself
A Service's selector matches 3 Pods, but one is not Ready. How many endpoints receive traffic?
- 3
- 2
- 1
- 0
Which Service type exposes the same port on every node?
- ClusterIP
- NodePort
- ExternalName
- Headless
What does clusterIP: None create?
- A broken Service
- A headless Service whose DNS returns Pod IPs
- A LoadBalancer
- A NodePort on port 0