Stage 7, Part 1 of 9, Kubernetes Networking Deep Dive

Text

PART 1: CORE THEORY

1. The Kubernetes Networking Model

Kubernetes networking is built on four fundamental rules that every Pod must satisfy.

The Four Rules

RuleMeaning
1. Pod-to-PodAny Pod can reach any other Pod without NAT
2. Pod-to-ServicePods can reach Services via stable ClusterIP
3. Node-to-PodNodes can reach Pods without NAT
4. External-to-ServiceExternal clients reach Services via NodePort/LoadBalancer/Ingress

The Networking Stack

text
┌─────────────────────────────────────────────────────────────┐
│                    KUBERNETES NETWORKING STACK              │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Pods (10.244.0.0/16)                               │   │
│  │  ┌─────────────┐  ┌─────────────┐                   │   │
│  │  │  Pod A      │  │  Pod B      │                   │   │
│  │  │  10.244.1.5 │  │  10.244.2.8 │                   │   │
│  │  └──────┬──────┘  └──────┬──────┘                   │   │
│  └─────────┼────────────────┼──────────────────────────┘   │
│            │                │                              │
│            ▼                ▼                              │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  CNI Plugin (Calico, Cilium, Flannel, VPC CNI)      │   │
│  │  • IP assignment                                    │   │
│  │  • veth pair creation                               │   │
│  │  • Cross-node routing                               │   │
│  │  • Network policy enforcement                       │   │
│  └─────────────────────────────────────────────────────┘   │
│            │                │                              │
│            ▼                ▼                              │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  kube-proxy (Service load balancing)                │   │
│  │  • iptables / IPVS / nftables                       │   │
│  │  • ClusterIP → Pod IP mapping                       │   │
│  └─────────────────────────────────────────────────────┘   │
│            │                                              │
│            ▼                                              │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Node Network (eth0, VPC, underlay)                  │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

The Pod Network CIDR

Every cluster has a Pod CIDR (e.g., 10.244.0.0/16) from which Pod IPs are allocated. Each node gets a slice (e.g., 10.244.1.0/24).

Important: The Pod CIDR must not overlap with:


2. CNI (Container Network Interface)

CNI is the plugin interface that Kubernetes uses to configure Pod networking.

What a CNI Plugin Does

FunctionDescription
IPAMAssigns IP addresses to Pods
veth pairsCreates virtual Ethernet pairs
RoutingPrograms cross-node routes
PolicyEnforces NetworkPolicy (optional)

The CNI Lifecycle

text
1. kubelet creates a Pod sandbox (network namespace)
2. kubelet invokes the CNI plugin with ADD command
3. CNI plugin:
   a. Allocates an IP from the Pod CIDR
   b. Creates a veth pair (one end in Pod, one on host)
   c. Configures routes so the Pod can reach other Pods
   d. Returns the IP to kubelet
4. kubelet starts the container in the sandbox

CNI Plugin Categories

CategoryExamplesApproach
OverlayFlannel (VXLAN)Encapsulates pod traffic
RoutingCalico (BGP)Programs routes natively
eBPFCiliumKernel-level networking
Cloud-nativeAWS VPC CNI, Azure CNIUses cloud VPC IPs
SimpleBridge, host-localBasic connectivity

CNI Requirements

RequirementWhy
Pod CIDRIP allocation range
Kernel modulesVXLAN, eBPF, etc.
Node permissionsNetwork namespace access
CNI config/etc/cni/net.d/

3. Service Networking

A Service provides a stable virtual IP (ClusterIP) that load-balances to a set of Pods.

The Four Service Types

TypeAccessibilityUse Case
ClusterIPInternal onlyService-to-service
NodePortVia Node IP + portDevelopment, on-prem
LoadBalancerCloud LBProduction external
ExternalNameDNS aliasExternal services

ClusterIP (Default)

yaml
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  type: ClusterIP
  selector:
    app: web
  ports:
  - port: 80
    targetPort: 8080

ClusterIP range: Typically 10.96.0.0/12 (configurable).

NodePort

yaml
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 8080
    nodePort: 30080

Range: 30000–32767 (default).

Access: <NodeIP>:30080.

LoadBalancer

yaml
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 8080

Provisions a cloud LB (AWS ELB/ALB/NLB, GCP LB, Azure LB).

ExternalName

yaml
spec:
  type: ExternalName
  externalName: db.example.com

DNS-only CNAME. No proxying.

How Service Load Balancing Works

text
Client → ClusterIP (10.96.0.10) → kube-proxy → Pod IP (10.244.1.5)
                                       │
                                       ├── iptables DNAT
                                       ├── IPVS virtual server
                                       └── eBPF map lookup

Service DNS

Every Service gets a DNS name:

text
<service>.<namespace>.svc.cluster.local

Examples:

Endpoints and EndpointSlices

The Service's backing Pods are tracked in EndpointSlice objects.

bash
kubectl get endpoints web
kubectl get endpointslices -l kubernetes.io/service-name=web

Empty endpoints = no Pods match the selector. This is the #1 cause of Service failures.


4. kube-proxy

kube-proxy is the component that implements Service load balancing on each node.

kube-proxy Modes

ModeMechanismScalability
iptablesiptables DNAT rulesPoor (linear with services)
IPVSIPVS virtual serversGood (hash-based)
nftablesnftables rulesModern (replaces iptables)

iptables Mode

Every Service creates iptables rules. As services grow, rules grow linearly:

text
10 services: 100 rules
100 services: 1,000 rules
1,000 services: 10,000 rules

Problem: Every packet traverses the chain. Performance degrades.

IPVS Mode

IPVS uses hash tables with O(1) lookup. Performance is stable regardless of service count.

IPVS advantages:

Performance difference: The main difference between IPVS and iptables is in TCP connection establishment. For short connections, IPVS is significantly faster. As Service and Endpoint counts increase, iptables performance drops while IPVS remains stable.

nftables Mode

nftables is the modern replacement for iptables. It's more efficient and has a cleaner syntax.

Kubernetes 1.31+ supports nftables mode in kube-proxy.

kube-proxy Components

ComponentPurpose
Service watcherWatches Service/Endpoint changes
Rule programmerWrites iptables/IPVS rules
Health checker(IPVS only) Probes backend health
Metrics exporterExposes Prometheus metrics

The kube-proxy Performance Problem

Even IPVS requires netfilter hooks and conntrack overhead. At high scale, this causes:

Solution: eBPF-based kube-proxy replacement (Cilium).


5. CoreDNS

CoreDNS is the cluster DNS server. Every Pod's /etc/resolv.conf points to the CoreDNS ClusterIP.

How CoreDNS Works

text
Pod → /etc/resolv.conf (nameserver 10.96.0.10)
    │
    ▼
CoreDNS (kube-dns Service)
    │
    ├── For cluster.local → returns Service/Endpoint IPs
    ├── For external domains → forwards to upstream DNS
    └── Caches responses

CoreDNS Configuration

Stored in the coredns ConfigMap in kube-system:

text
.:53 {
    errors
    health
    ready
    kubernetes cluster.local in-addr.arpa ip6.arpa {
        pods insecure
        fallthrough in-addr.arpa ip6.arpa
        ttl 30
    }
    prometheus :9153
    forward . /etc/resolv.conf
    cache 30
    loop
    reload
    loadbalance
}

Key CoreDNS Plugins

PluginPurpose
kubernetesServes cluster.local records
forwardForwards external queries
cacheCaches responses
healthHealth endpoint
prometheusMetrics
loopDetects forwarding loops
reloadAuto-reload config

Pod DNS Configuration

text
nameserver 10.96.0.10
search default.svc.cluster.local svc.cluster.local cluster.local
options ndots:5

The ndots:5 problem: Any name with fewer than 5 dots triggers search-domain expansion.

For api.stripe.com (2 dots < 5):

  1. api.stripe.com.default.svc.cluster.local → NXDOMAIN
  2. api.stripe.com.svc.cluster.local → NXDOMAIN
  3. api.stripe.com.cluster.local → NXDOMAIN
  4. api.stripe.com. → Success

One logical lookup = 4 wire queries.

NodeLocal DNSCache

NodeLocal DNSCache runs a DNS cache on every node as a DaemonSet.

BenefitExplanation
Bypasses conntrackUDP → TCP conversion
Eliminates 5s timeoutNo UDP conntrack race
Sub-ms cache hitsNever leaves the node
Reduces CoreDNS load80–95% fewer queries

Architecture:

text
Pod → 169.254.20.10 (NodeLocal DNSCache) → TCP → CoreDNS
        │
        └── Cache hit: answer locally
        └── Cache miss: forward to CoreDNS over TCP

1:1 copy of the class Google Doc, code in code blocks.