Sub topic 2
Pod IPs, Labels and Selectors
This chapter assumes you can apply YAML manifests with kubectl and know what Pods, Deployments and Namespaces are. It also assumes you know what an IP address and a port are. Services depend on two ideas covered here: Pod IPs change, and labels let you group Pods without naming them.
Pod IPs are real but short-lived
Every Pod gets its own IP address from the cluster network. Other Pods can reach it directly, with no NAT in between. That is part of the Kubernetes network model.
The address belongs to that Pod instance, not to your application. When a Pod is deleted, evicted or replaced during a rollout, its replacement gets a new IP. A Deployment that scales from 3 to 5 replicas adds two new addresses. A client that stores a Pod IP will break the first time the Pod restarts somewhere else.
You can see the addresses with the wide output format:
kubectl get pods -o wideRun kubectl delete pod on one of them and list the Pods again. The new Pod has a different IP.
Labels
A label is a key-value pair attached to an object's metadata. Labels carry no meaning for Kubernetes by themselves. You choose them to describe your own groupings, such as app: web, tier: backend or env: prod.
In a Deployment, the labels that matter are in the Pod template:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: nginx:1.27
ports:
- name: http
containerPort: 80
readinessProbe:
httpGet:
path: /
port: httpEvery Pod this Deployment creates carries app=web. Replacement Pods carry it too, so the label stays constant while the IPs change.
Selectors
A selector is a query over labels. The Deployment's spec.selector.matchLabels tells it which Pods it owns. A Service uses the same mechanism to decide which Pods receive traffic.
Selectors are also available on the command line:
kubectl get pods -l app=web
kubectl get pods -l 'app in (web, api)'
kubectl get pods --show-labelsEquality-based selectors (app=web) and set-based selectors (app in (web, api)) are both supported. When you list several requirements, a Pod must match all of them.
Common errors
- Selector and template labels differ. If a Deployment's
selector.matchLabelsdoes not match its template labels, the API server rejects it. - Typos in labels. A Service selecting
app: webbmatches nothing. Kubernetes accepts it without any error. - Overlapping labels. Two Deployments that both create Pods labeled
app=webcan be selected together by one Service, which is rarely intended.
Exercise
A Pod's IP changes every time it is recreated. What stays the same across replacement Pods from one Deployment, and how can another object use it to find them?
Show answer
The labels in the Pod template, such as app=web, stay the same. Another object, such as a Service, uses a selector that matches those labels, so it finds the current Pods regardless of their IPs.