Pods, Deployments and Services
The core objects, the reconciliation loop, labels and selectors, and how a request finds a pod.
Kubernetes is a control loop: you write down the state you want, in YAML, and controllers work continuously to make the cluster match it. Everything else — pods, deployments, services — is the vocabulary for describing that state. This lesson is the four objects a backend service is made of and what each one is actually for, because most of the confusion in the first month comes from mistaking one for another.
Pods: the unit that runs
A pod is one or more containers that share a network namespace (one IP, one localhost) and can share volumes. It is the smallest thing Kubernetes schedules, and it is disposable: a pod that dies is not restarted, it is replaced, with a new name and a new IP. That is the property to internalise before anything else, because it rules out every design that remembers a pod — a sticky session, a local cache that matters, a file written to the pod's disk.
Most pods have one container. The second container, when there is one, is a sidecar: a log shipper reading the application's files, a proxy handling TLS, a Debezium-style agent — something that must share the pod's network or disk. An init container runs to completion before the main one starts: a migration, a chown on a volume, a wait for a dependency.
Deployments and ReplicaSets: how many, and which version
You almost never create a pod directly. A Deployment says "three replicas of this pod template", and its controller creates a ReplicaSet that keeps three running — a pod dies, the ReplicaSet makes another; a node dies, its pods are rescheduled elsewhere:
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders-api }
spec:
replicas: 3
selector: { matchLabels: { app: orders-api } }
template:
metadata: { labels: { app: orders-api, version: "1.14.2" } }
spec:
containers:
- name: api
image: registry.example.com/orders-api:1.14.2
ports: [{ containerPort: 8080 }]Change the image tag and the Deployment creates a new ReplicaSet for the new template and scales the old one down as the new one comes up — the rolling update the rollouts lesson covers. The old ReplicaSet stays at zero replicas, which is what kubectl rollout undo scales back up. So a Deployment is a version history of ReplicaSets, and a ReplicaSet is a pod count; neither is the thing traffic reaches.
A StatefulSet is the sibling for things that do need a stable identity — postgres-0, kafka-1 — with a persistent volume per replica and ordered start-up. A DaemonSet runs one pod per node (log collectors, node agents). A Job runs to completion; a CronJob runs one on a schedule. A Spring Boot API is a Deployment; the database it talks to is usually outside the cluster or a StatefulSet run by an operator, and the Docker course's warning about databases on disposable disks applies doubly here.
Services: a stable name for a moving set
Pods have IPs that change; a Service is the fixed address in front of them. It selects pods by label and keeps an endpoint list of the ones that are ready:
apiVersion: v1
kind: Service
metadata: { name: orders-api }
spec:
selector: { app: orders-api }
ports: [{ port: 80, targetPort: 8080 }]Inside the cluster, http://orders-api (or orders-api.<namespace>.svc.cluster.local) resolves through cluster DNS to the Service's ClusterIP, and kube-proxy load-balances connections across the endpoints. That is the whole of service discovery for most systems, and the microservices course's discovery lesson said so: in Kubernetes it is DNS. Two things it does not do, both from the gRPC lesson: it balances connections, not requests, so one long-lived HTTP/2 connection goes to one pod; and a headless Service (clusterIP: None) returns the pod IPs instead, for clients that balance themselves.
type: NodePort opens a port on every node; type: LoadBalancer asks the cloud for an external load balancer pointed at those. Neither is how a web service is usually exposed, because each costs a load balancer per Service; that is what Ingress is for.
Ingress: HTTP from outside, routed by host and path
An Ingress is a routing table for HTTP — this host and path go to that Service — implemented by an ingress controller (nginx, Traefik, the cloud's own) that is itself a Deployment behind one LoadBalancer Service:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: code10x
annotations: { nginx.ingress.kubernetes.io/proxy-body-size: "8m" }
spec:
tls: [{ hosts: ["code10x.in"], secretName: code10x-tls }]
rules:
- host: code10x.in
http:
paths:
- path: /api
pathType: Prefix
backend: { service: { name: orders-api, port: { number: 80 } } }
- path: /
pathType: Prefix
backend: { service: { name: site, port: { number: 80 } } }That is this repository's nginx configuration — /api to the Java service, everything else to the static site, TLS at the edge, a body-size limit on uploads — written as an object the cluster manages instead of a file on a host. The annotations are where the controller's specifics live (timeouts, buffering, forwarded headers, the things the nginx lesson covers), which is also the trap: annotations are per controller and do not port. The Gateway API is the newer, portable version of the same idea and is where new clusters are heading.
Labels: the glue
Every relationship above is a label selector: the Deployment finds its pods by app: orders-api, the Service finds its endpoints the same way, and kubectl get pods -l app=orders-api finds them for you. Labels are free-form key-value pairs, and a consistent set — app, version, team, environment — is what makes a cluster navigable and what makes the observability course's dashboards possible, because the metrics and logs carry the same labels. Annotations are the other kind of metadata: for tools, not for selection.
Namespaces partition a cluster — orders, payments, monitoring — with their own names, quotas and access rules; a Service is orders-api in its namespace and orders-api.orders from another.
Under the hood: what a ClusterIP actually is, and why a pod has one IP
"kube-proxy load-balances connections across the endpoints" hides two mechanisms worth naming, because they are what you read when a Service is not working.
kube-proxy: a rule-writer, not a proxy in the data path
Despite its name, kube-proxy does not sit in the middle of every connection in its default modes. It watches the API server for Service and EndpointSlice objects and, on every change, rewrites kernel packet-filtering rules — it programs the data path once, then gets out of the way:
- iptables mode (the long-standing default): for each Service, kube-proxy inserts a rule in the kernel's
KUBE-SERVICESchain that matches the ClusterIP and port, and jumps to a per-Service chain holding one rule per ready endpoint, selected with iptables'statisticrandom-probability match — an approximation of round-robin picked by the kernel, not by a process reading each packet. The matching rule DNATs the packet: it rewrites the destination from the ClusterIP to a real pod IP before the kernel routes it, and Linux's connection tracking (conntrack) remembers that rewrite so the reply is translated back automatically. A ClusterIP is a virtual address that never appears on any interface; connecting to it works because the kernel rewrites the destination before the packet leaves the box, not because something is listening on it. - IPVS mode: kube-proxy instead creates virtual servers in the kernel's IP Virtual Server subsystem, a real load balancer built into Linux netfilter, with actual scheduling algorithms (round-robin, least-connection, and others) and O(1) rule lookup — the alternative for clusters with enough Services that iptables' linear chain-of-rules matching starts to cost CPU on every packet.
Either way, the endpoint list a Service load-balances over is only the pods currently passing readiness — a pod that fails its readiness probe is removed from EndpointSlices, and kube-proxy's next sync deletes its DNAT rule, so no new connection is routed to it (existing ones are untouched, which is one reason a slow-to-notice readiness failure still drains gradually rather than instantly).
The pause container: why containers in a pod share one IP
A pod's "one IP, one localhost" is not a Kubernetes-level abstraction layered on top of separate containers — it is one real Linux network namespace, and the mechanism is a small, otherwise-invisible container. When the kubelet creates a pod, it first starts an infrastructure container (pause) whose only job is to hold that network namespace open; the binary itself does nothing but wait. Every other container in the pod is then started joined to that same network namespace — the CRI equivalent of Docker's --net=container:<pause-id> — rather than getting one of its own. That is the entire mechanism behind "one IP, one localhost, ports must not collide": it is namespace sharing, and the pause container is the thing that keeps the namespace alive across app-container restarts, so a crashing and restarting main container does not also lose the pod's IP.
What is not shared by default is the PID namespace — each container still has its own process tree, pid 1 and all, unless the pod sets shareProcessNamespace: true — which is why kubectl exec into one container of a multi-container pod does not show the other container's processes even though curl localhost:<port> reaches it.
Try it yourself
Predict what happens to routing when a pod fails readiness
A Service orders-api has four pods behind it, all Running, all currently passing readiness. kube-proxy is in iptables mode, so its per-Service chain has four KUBE-SEP-* rules, each with roughly 25% probability. One pod's readiness probe starts failing (its dependency is down), while the pod keeps running and keeps its existing connections open.
Using the mechanism described above — EndpointSlices, kube-proxy's sync, and conntrack — predict: (1) does the failing pod's existing open connections get cut, and (2) does a new connection ever get routed to it again while it is not ready?
Why an unready pod keeps old connections but never gets a new one
The kubelet's readiness check going from success to failure updates the pod's readiness condition, which removes it from the Service's EndpointSlice. kube-proxy's watch loop notices the EndpointSlice change and, on its next sync, deletes that pod's KUBE-SEP-* rule from the per-Service chain (and removes it from the IPVS virtual server's real-server list, in IPVS mode) — leaving three rules with roughly 33% probability each. That rewrite only affects new DNAT decisions: it changes which pod a new connection's opening packet gets rewritten to. A connection that is already established has already been DNAT'd once, and conntrack keeps translating packets for that specific connection to the same pod IP regardless of whether the pod is still in the Service's rule set — so existing connections are left alone (they drain, or fail, on their own) while every new connection goes only to the three remaining ready pods.
Misconceptions
- "A ClusterIP is a real address something listens on." Nothing binds to it. It exists only as a kernel rule (an iptables DNAT rule or an IPVS virtual server) that rewrites the destination of a packet addressed to it before the kernel routes that packet onward;
pinging a ClusterIP typically gets no reply because ICMP is not what the rule matches. - "Containers in a pod share a network namespace because Kubernetes virtualises it." They share it because the container runtime literally starts them inside the same Linux network namespace the
pausecontainer created and holds open — the same primitivedocker run --net=container:<id>uses, with nothing Kubernetes-specific about the underlying mechanism.
Sources
- Kubernetes documentation, "Service" concept page — ClusterIP, EndpointSlices, and the
iptablesandIPVSkube-proxy proxy modes. - Kubernetes documentation, "Pods" concept page — the pod networking model and the infrastructure (pause) container.
- Kubernetes documentation, "kube-proxy" reference page — proxy mode selection and how each mode programs the kernel.