How does a Kubernetes Service provide stable networking to ephemeral Pods, and what is the difference between ClusterIP and NodePort?
Quick Answer
A Service assigns a stable virtual IP and DNS name to a dynamic set of Pods selected by labels. kube-proxy (or eBPF dataplane) routes traffic to healthy endpoints. ClusterIP is internal-only; NodePort exposes the Service on each node's IP at a static high port.
Detailed Answer
Pods come and go. Their IP addresses change every time they are rescheduled. Clients cannot reliably connect to Pod IPs directly. A Kubernetes Service solves this by introducing a stable front door—a virtual IP (ClusterIP) and a DNS record such as payments-api.default.svc.cluster.local—that persists regardless of which Pod instances are currently running behind it.
The Service controller watches Endpoints (or EndpointSlices) objects that list the current Pod IPs matching the Service's label selector. When a new Pod passes its readiness probe, it is added to endpoints. When a Pod terminates, it is removed. kube-proxy on each node programs iptables or IPVS rules—or a CNI like Cilium uses eBPF—to forward traffic destined for the Service VIP to one of the healthy backend Pods, typically using round-robin or session affinity.
ClusterIP is the default type and is reachable only inside the cluster. It is ideal for east-west communication: checkout-worker calling payments-api without exposing the API to the public internet. NodePort allocates a port in the 30000–32767 range on every node and forwards inbound traffic to the Service. It is useful for bare-metal labs or when you lack a cloud load balancer, but production clusters usually prefer LoadBalancer or Ingress for external access.
Think of a Service like a restaurant host stand. Patrons ask for 'payments-api,' not for 'table 7.' The host (Service) checks which tables (Pods) are ready and seats guests accordingly. If a waiter leaves (Pod dies), the host redirects new guests to another ready table without changing the restaurant's street address (Service DNS).
Key interview concepts include headless Services (clusterIP: None) for StatefulSet direct Pod DNS, externalName for CNI-less DNS aliasing, and the importance of readiness probes in keeping not-yet-ready Pods out of the endpoint pool.
Session affinity (sessionAffinity: ClientIP) pins a client to the same backend Pod for the session timeout duration—useful for legacy apps that store session state in memory. ExternalIPs and LoadBalancer types extend reachability for hybrid scenarios, though cloud integrations vary by provider. For payments-api with 3 replicas, a ClusterIP Service on port 80 distributes traffic evenly once all Pods report Ready.