Skip to content

Kubernetes Networking: Pod Network & CNI, ClusterIP/NodePort/LoadBalancer, kube-proxy (iptables/IPVS), CoreDNS, Ingress & Gateway API, NetworkPolicy, Egress NAT ​

"Pods can communicate with each other directly, without the use of proxies or address translation (NAT)." — Kubernetes documentation, Services, Load Balancing, and Networking (the Kubernetes network model)

Summary: Kubernetes gives every pod its own IP on a flat network, puts a virtual IP and a DNS name in front of every group of pods, and lets you bolt on HTTP routing, firewall rules and egress control as separate API objects; each piece is implemented by a different component on every node. Focus: The data path: pod network namespaces and CNI plugins, Services and the iptables/nftables/IPVS/eBPF rules behind a ClusterIP, NodePort, LoadBalancer and traffic policies, CoreDNS and ndots, Ingress and Gateway API, NetworkPolicy, egress SNAT, and how to debug every hop. Learning goal: Trace any request in a cluster hop by hop (which component rewrites which address), predict what the pod sees as the client IP, read iptables-save and EndpointSlices, and fix the ten failures every team meets.

This chapter is the Kubernetes data path, written for a developer who ships services into a cluster and has to debug them. It assumes the layers below it: addresses and subnets in IP addressing and CIDR, translation tables in NAT and port forwarding, resolvers and resolv.conf in DNS resolution for developers, sockets and conntrack in ports, sockets and connections, netfilter chains in firewalls, iptables and nftables, and the single-host version of all of this in Docker networking. Certificates on Ingress and Gateway listeners are in TLS in practice; a symptom-first view is the network troubleshooting playbook. The design questions sit one level up and are linked, not repeated: client-side vs server-side discovery in service discovery, gateways, BFFs and meshes in API gateway, BFF and service mesh, L4 vs L7 balancing in load balancing, the cluster as a platform in containers and Kubernetes, sidecars in service mesh and the sidecar pattern, and mTLS in mutual TLS.

Page map ​

If you are looking forGo to
The tables to memoriseEverything in one minute
Why pods get their own IPs, the four networking problemsWhy Kubernetes networking looks like this
Versions, deprecations, the CNI spec, Ingress freezeWhere it comes from
Pause container, veth, pod CIDR, CNI ADD/DELPods and the pod network, CNI plugins
VXLAN vs Geneve vs BGP vs eBPF, MTUOverlay, routed and eBPF datapaths
ClusterIP, the VIP nobody ownsServices and ClusterIP
EndpointSlices, ready/serving/terminatingEndpointSlices
iptables, nftables, IPVS, Cilium kube-proxy replacementkube-proxy modes
Session affinity, headless, ExternalNameSession affinity, Headless Services, ExternalName
NodePort 30000-32767, LoadBalancer, MetalLB, cloud LBsNodePort, LoadBalancer
Client IP lost, externalTrafficPolicy, internalTrafficPolicyTraffic policies
Topology-aware routing, trafficDistributionTopology-aware routing
CoreDNS, Corefile, ndots:5, dnsPolicy, NodeLocal DNSCacheCluster DNS
Ingress controllers and annotationsIngress
GatewayClass, Gateway, HTTPRoute, GRPCRouteGateway API
Default deny, allow DNS, namespace isolation, Cilium L7NetworkPolicy
SNAT, egress gateways, NAT gateways, conntrackEgress
hostNetwork, hostPort, dual-stack, mesh overlap, port-forwardhostNetwork, Dual-stack, Service mesh, port-forward
One packet, hop by hop; real iptables-save; hex dumpMechanics
Go and Laravel code for the lab and for productionSolving the classic problems
Symptom → cause → fixCommon failures
Which option for which situationChoosing
Monolith to distributedIn architecture
Reproduce everything on kindLab

Everything in one minute ​

The objects and who implements them. Every row is unpacked below.

ThingIn plain wordsTiny exampleImplemented by
Pod IPEvery pod is a little host with its own address10.244.1.5CNI plugin (kindnet, Calico, Cilium, flannel, AWS VPC CNI)
Pod CIDREach node owns a slice of the pod rangenode A 10.244.1.0/24kube-controller-manager IPAM or the CNI's own IPAM
Service (ClusterIP)A stable virtual IP + port in front of changing pods10.96.84.19:80 → 3 podsAPI server allocates; kube-proxy or Cilium programs every node
EndpointSliceThe live list of ready pod IPs behind a Service10.244.1.5:8080 ready=trueEndpointSlice controller
NodePortSame port opened on every nodenode:30080 → Servicekube-proxy
LoadBalancerAn external IP in front of the NodePorts (or pods)203.0.113.10:80Cloud controller, AWS LBC, MetalLB, cloud-provider-kind
Cluster DNSNames for Services and podswhoami.lab.svc.cluster.localCoreDNS (+ NodeLocal DNSCache)
IngressHTTP host/path routing into Services (frozen API)shop.example.com/api → api:80An ingress controller (ingress-nginx, Traefik, HAProxy, cloud)
Gateway APIRole-split, typed successor of IngressHTTPRoute 90/10 canaryEnvoy Gateway, Istio, Cilium, NGINX Gateway Fabric, cloud
NetworkPolicyPod-level firewall by labelsdefault deny + allow DNSThe CNI plugin (if it supports it)
Egress SNATTraffic leaving the cluster wears the node's IPpod → internet as 172.18.0.3Node masquerade, cloud NAT gateway, egress gateway

Service types at a glance.

TypeReachable fromAddressWho answers
ClusterIP (default)Inside the clusterVirtual IP from the service CIDRkube-proxy rules on the client's node
Headless (clusterIP: None)Inside the clusterNo VIP; DNS returns pod IPsThe pods directly
NodePortAnything that reaches a nodenodeIP:30000-32767kube-proxy on the receiving node
LoadBalancerOutside (internet or VPC)External IP / hostname in status.loadBalancerCloud LB or MetalLB, then NodePort or pod IPs
ExternalNameInside the clusterDNS CNAME onlyWhatever the CNAME points to

kube-proxy modes (Kubernetes v1.37).

ModeStatusData structureNotes
iptablesDefault on LinuxLinear chains KUBE-SERVICES → KUBE-SVC-* → KUBE-SEP-*Random endpoint via -m statistic
nftablesStable; recommended replacement for ipvs; future defaultnftables maps/setsNeeds kernel 5.13+; NodePorts only on primary IPs by default
ipvsDeprecated since v1.35; off by default from v1.40; removed in v1.43Kernel IPVS hash tablesMany schedulers (rr, lc, sh, mh)
kernelspaceWindows onlyWindows HNS
Cilium kube-proxy replacementNot kube-proxy at alleBPF maps, socket-level LBkubeProxyReplacement=true, Maglev, DSR

Why Kubernetes networking looks like this ​

Docker on one host gives each container a private IP behind NAT and publishes ports with -p. Across many hosts that breaks: two apps want port 8080, every service must learn its peers' host ports, and addresses change as containers move. The Kubernetes cluster networking page frames it as "4 distinct networking problems to address": container-to-container (solved by pods sharing localhost), pod-to-pod, pod-to-Service and external-to-Service. Kubernetes' answer is to make a pod look like a small VM: its own IP, its own port space, reachable from every other pod without NAT, and then to add stable names and virtual IPs on top. The docs: "pods can be treated much like VMs or physical hosts from the perspectives of port allocation, naming, service discovery, load balancing, application configuration, and migration."

The model has three requirements, quoted from the network model:

RequirementWhat it means for you
"Each pod in a cluster gets its own unique cluster-wide IP address."Two pods can both listen on 8080; no port mapping inside the cluster
"All pods can communicate with all other pods ... directly, without the use of proxies or address translation (NAT)."The source IP a pod sees from another pod is that pod's real IP
"Agents on a node (such as system daemons, or kubelet) can communicate with all pods on that node."Probes from the kubelet reach the pod; NetworkPolicy always allows the node

What Kubernetes itself implements is small; the rest is plugged in:

Kubernetes definesSomeone else implements
Pod IPs, pod networkContainer runtime (containerd, CRI-O) calling a CNI plugin
Service, EndpointSlicekube-proxy (or Cilium, Calico eBPF, OVN-Kubernetes)
Service DNS schemaCoreDNS (any conforming DNS server)
type: LoadBalancerCloud controller manager, AWS Load Balancer Controller, MetalLB
Ingress, Gateway APIAn ingress controller or Gateway implementation
NetworkPolicyThe CNI plugin, if it enforces policy

The analogy we reuse on this page: an office building. Every room (pod) has its own phone extension (pod IP); any room can dial any other directly. Departments publish one reception number (Service ClusterIP) that rings whichever clerk is on duty; there is no physical phone with that number, every floor's switchboard (kube-proxy on each node) just knows how to forward it. The internal directory (CoreDNS) maps "billing" to the reception number. The front desk (Ingress/Gateway) routes visitors by the name on their appointment. Badge rules (NetworkPolicy) say which rooms may call which. And every outgoing call shows the building's main number (egress SNAT), not the room's extension.

Three common misunderstandings, up front ​

  1. "The ClusterIP is a load balancer box somewhere." No process listens on it and no interface owns it. It is a match rule in iptables/nftables (or an eBPF map) on every node, applied to packets as they leave the client pod. That is why ping to a ClusterIP usually fails while TCP to its port works.
  2. "A Service balances requests." kube-proxy balances connections. With HTTP keep-alive or gRPC, one client stays pinned to one pod for the life of the connection. Request-level balancing needs an L7 proxy (Ingress, Gateway, mesh) or client-side balancing over a headless Service.
  3. "The pod sees the real client IP." Inside the cluster yes; from outside, by default, no: NodePort and LoadBalancer traffic is SNATed to a node IP unless you set externalTrafficPolicy: Local or read X-Forwarded-For from a trusted proxy.

Where it comes from ​

The pieces arrived at different times, and several are being replaced while you read this. Versions below come from the pages linked in References, which document Kubernetes v1.37.

Year / versionEventSource
CNI spec v0.1.0 → v1.xRuntime ↔ plugin contract: ADD, DEL, later CHECK (v0.4.0), STATUS, GC; "plugin chaining" from v0.3.0CNI SPEC.md
Kubernetes 1.3 → today"Kubernetes (version 1.3 through to the latest 1.37, and likely onwards) lets you use Container Network Interface (CNI) plugins"Network plugins page
v1.28iptables mode only rewrites changed Services/EndpointSlices instead of the whole tableVirtual IPs page
v1.29 → v1.33nftables mode "introduced as an alpha feature in Kubernetes 1.29", expected GA in 1.33Kubernetes blog, Feb 2025
v1.33Endpoints API deprecated in favour of EndpointSliceServices page
v1.35IPVS mode deprecated; "disabled by default from Kubernetes v1.40", "fully removed in Kubernetes v1.43"Virtual IPs page
v1.36externalIPs deprecated: "All users should begin migrating away from externalIPs."Services page
v1.37Default proxy mode is still iptables; "a future version of Kubernetes will change the default to nftables"Virtual IPs page
Ingress"The Kubernetes project recommends using Gateway instead of Ingress. The Ingress API has been frozen."Ingress page
March 2026Ingress NGINX (the kubernetes/ingress-nginx controller) retired: "no further releases, no bugfixes, and no updates to resolve any security vulnerabilities"Kubernetes blog, Nov 2025

The reason Services use virtual IPs and proxies instead of plain round-robin DNS is spelled out in the docs: DNS implementations that ignore TTLs, apps that "do DNS lookups only once and cache the results indefinitely", and the load very low TTLs would put on DNS. Keep that in mind when you meet headless Services, which deliberately go the DNS way.

The concept catalogue ​

Each block: plain words, the usual wrong belief, a definition, a timeline or packet flow, real scenarios, per-product behaviour, then the fix or usage with links to the code in Solving the classic problems.

Node A eth0 172.18.0.3 podCIDR 10.244.1.0/24Node B eth0 172.18.0.4 podCIDR 10.244.2.0/24Pod whoami-a (netns)pauseapp :8080lo 127.0.0.1 (shared)eth0 10.244.1.5Pod netshoot (netns)pausenetshooteth0 10.244.1.6vethA1vethA2bridge cni0 / per-pod /32 routes (CNI plugin)kube-proxy rules + conntrack live hereroute 10.244.2.0/24 via 172.18.0.4 (routed)or dev vxlan / geneve (overlay, MTU -50)Pod whoami-b (netns)pauseapp :8080eth0 10.244.2.7hostNetwork podno own netns:uses node eth0172.18.0.4vethB1bridge / routes / eBPF programskube-proxy rules + conntrack live hereroute 10.244.1.0/24 via 172.18.0.3 (routed)or dev vxlan / geneve (overlay)Underlay: node network (VPC, LAN, Docker bridge for kind)overlay: outer IP 172.18.0.3 -> 172.18.0.4, UDP 8472 (VXLAN) or 6081 (Geneve)routed: inner packet 10.244.1.5 -> 10.244.2.7 travels as-is (BGP, cloud routes)pod to pod: no NAT either way

Pods and the pod network Must-know ​

In plain words: a pod is one network namespace: one IP, one localhost, one port space, shared by all its containers. A tiny "pause" container holds that namespace open so app containers can restart without the pod losing its IP.

Common misunderstanding: "Each container in the pod has its own IP." No. Containers in a pod talk over 127.0.0.1 and must not both bind the same port; a sidecar on :15001 and your app on :8080 share one eth0.

Definition: the CRI runtime creates the pod sandbox (the pause container's network namespace), then calls the CNI plugin to give it an interface. The CNI spec: "The container runtime must create a new network namespace for the container before invoking any plugins." A typical bridge-style plugin creates a veth pair: one end becomes eth0 inside the pod, the other stays on the node and is attached to a bridge (cni0) or gets a /32 route. The node routes the rest of the cluster's pod CIDR toward other nodes.

text
kubelet -> containerd: RunPodSandbox(whoami-abc)
1  containerd starts pause, creates netns /var/run/netns/cni-1234
2  containerd -> CNI plugin: ADD  CNI_NETNS=/var/run/netns/cni-1234 CNI_IFNAME=eth0
3  plugin: create veth pair (eth0 in pod, vethXXXX on node), IPAM picks 10.244.1.5/24
4  plugin: route 10.244.1.5 dev vethXXXX on the node; default route via 10.244.1.1 in the pod
5  plugin -> containerd: result {ips:[10.244.1.5/24], routes:[0.0.0.0/0]}
6  kubelet: status.podIP = 10.244.1.5; app containers start in the same netns
   ... pod deleted ...
7  containerd -> CNI plugin: DEL   (address returned to IPAM, veth removed)

Real scenario: an Istio sidecar intercepts traffic because it lives in the same namespace as your app; a log-shipper sidecar reaches your app's metrics on localhost:9090; a pod stuck in ContainerCreating with failed to set up sandbox container ... network means the CNI ADD failed (plugin not installed, IPAM exhausted).

ProductHow a pod is wired
kindnet (kind default)veth + per-pod route, simple routed pod CIDRs between nodes
flannelveth + cni0 bridge, VXLAN between nodes by default
Calicoveth + /32 routes (no bridge), BGP or VXLAN/IP-in-IP between nodes, or eBPF dataplane
Ciliumveth + eBPF programs on each veth, VXLAN/Geneve or native routing
AWS VPC CNIPod gets a real VPC IP from the node's ENIs; no overlay
Azure CNI / GKE VPC-nativePod IPs from VNet/VPC (alias IP) ranges; routed by the cloud

How to use it: read a pod's IP with the downward API (status.podIP, used by the whoami service); never hard-code pod IPs, they change on every reschedule; talk to peers in the same pod over localhost.

CNI plugins, IPAM and the pod CIDR Must-know ​

In plain words: CNI is a tiny contract: the runtime runs a binary from /opt/cni/bin with a JSON config from /etc/cni/net.d and environment variables, and the binary wires the pod up and prints the result.

Common misunderstanding: "Kubernetes picks pod IPs." The API server picks Service IPs; pod IPs come from the CNI plugin's IPAM (often from the node's spec.podCIDR, which kube-controller-manager assigns from --cluster-cidr). Run out of addresses in a node's /24 (254 pods) or a VPC subnet and pods stay ContainerCreating.

Definition: the CNI spec defines operations ADD, DEL, CHECK, STATUS, VERSION and GC, parameters such as CNI_COMMAND, CNI_CONTAINERID, CNI_NETNS ("a path to the network namespace") and CNI_IFNAME, and chaining (plugins: [...], each receiving prevResult). Kubernetes requires "a CNI plugin that is compatible with the v0.4.0 or later releases of the CNI specification" and recommends v1.0.0. Helper plugins: loopback, portmap (for hostPort), bandwidth (traffic shaping).

text
/etc/cni/net.d/10-mynet.conflist  (example chain: plugins run in order on ADD, reverse on DEL)
1  ptp       -> veth pair + host-local IPAM from the node's podCIDR
2  portmap   -> hostPort DNAT rules (capability: portMappings)

Real scenario: EKS nodes hit the per-instance ENI/IP limit long before CPU is full; a cluster built with --cluster-cidr 10.0.0.0/16 collides with the corporate VPN's 10.0.0.0/8 and some pods cannot reach on-prem; a Calico IP pool is exhausted after scaling nodes because each node grabbed a /26 block.

RangeSet whereDefault in kind
Pod CIDR (cluster)--cluster-cidr (controller-manager) / CNI config10.244.0.0/16
Pod CIDR (per node)node.spec.podCIDR/24 per node
Service CIDR--service-cluster-ip-range (API server), ServiceCIDR objects10.96.0.0/16 (kind default)
Node IPsKubelet / cloudDocker network 172.18.0.0/16 in kind

How to use it: plan three non-overlapping ranges (nodes, pods, Services) against every network the cluster must reach; check a node's slice with kubectl get nodes -o custom-columns=NAME:.metadata.name,CIDR:.spec.podCIDR.

Overlay, routed and eBPF datapaths; MTU Important ​

In plain words: a packet from a pod on node A to a pod on node B either travels wrapped in another packet between the nodes (overlay), or travels as-is because the network knows where each pod CIDR lives (routed). eBPF plugins replace the Linux bridge/iptables plumbing with programs, and can use either.

Common misunderstanding: "Overlay is always slow." The extra header costs bytes (and some CPU), but the common real bug is not speed; it is MTU: if the pod MTU is not reduced by the encapsulation overhead, large packets are dropped while small ones work.

Definition:

ModeHow it crosses nodesNeeds from the networkOverheadProducts
VXLAN overlayInner Ethernet frame in UDP (Cilium/flannel use 8472/UDP)Node-to-node UDP50 bytes per packet (IPv4)flannel default, Cilium default, Calico option
Geneve overlayLike VXLAN with extensible options, 6081/UDPNode-to-node UDP50+ bytesCilium option, OVN-Kubernetes
IP-in-IPIPv4 inside IPv4 (protocol 4)Protocol 4 allowed (often blocked in clouds)20 bytesCalico
Native / routedInner packet unchanged; routes to each podCIDRBGP peering or cloud route tables0Calico BGP, Cilium native routing, kindnet
Cloud VPC-nativePod IPs are VPC IPsCloud IPAM0AWS VPC CNI, GKE VPC-native, Azure CNI
Cross-subnetRouted inside a subnet, encapsulated across subnetsMixed0 or 20/50Calico CrossSubnet

Cilium's docs on encapsulation: "the effective MTU available for payload is lower than with native-routing (50 bytes per network packet for VXLAN)". Calico's MTU guide: "IP in IP uses a 20-byte header" and lists 1450 for VXLAN on a 1500 network.

text
Pod A 10.244.1.5 -> Pod B 10.244.2.7, VXLAN overlay, underlay MTU 1500
1  pod A sends 1500-byte IP packet (pod MTU wrongly left at 1500)
2  node A wraps it: outer IP 172.18.0.3 -> 172.18.0.4, UDP 8472, VXLAN header = 1550 bytes
3  underlay link MTU 1500: packet too big; DF set -> ICMP "frag needed" or silent drop
4  TCP handshake (small packets) works; first large response hangs -> "curl hangs after headers"
fix: pod MTU 1450 (CNI setting), or jumbo frames on the underlay

Real scenario: curl to a service on another node hangs exactly when the response is larger than ~1400 bytes; TLS handshakes stall at the certificate message; a VPN or WireGuard (Calico/Cilium encryption) adds its own overhead on top of VXLAN.

How to use it: check the pod MTU with kubectl exec POD -- ip link show eth0 and compare to the node's; test with ping -M do -s 1422 POD_IP (1422 + 28 = 1450). Fix it in the CNI configuration, not in the app. Details and the generic method are in the troubleshooting playbook.

Client pod10.244.1.6:41234connect 10.96.84.19:80nat PREROUTING / OUTPUT-j KUBE-SERVICES(no interface owns 10.96.84.19)KUBE-SERVICES-d 10.96.84.19/32 -p tcp --dport 80-j KUBE-SVC-XXXXXXXXXXXXXXXXKUBE-SVC-XXXX (one per Service port)! -s 10.244.0.0/16 -j KUBE-MARK-MASQ (off-cluster source: SNAT later)-m statistic --probability 0.333 -j KUBE-SEP-A-m statistic --probability 0.500 -j KUBE-SEP-B ; -j KUBE-SEP-CKUBE-SEP-ADNAT 10.244.1.5:8080KUBE-SEP-BDNAT 10.244.2.7:8080KUBE-SEP-CDNAT 10.244.2.8:8080Control plane feeds itService: selector app=whoamiEndpointSlice controller:ready pod IPs -> sliceskube-proxy on EVERY nodewatches both and rewritesiptables / nftables / IPVS(or Cilium eBPF maps)conntrack: one entry per connection, decision made onceorig 10.244.1.6:41234 -> 10.96.84.19:80reply 10.244.2.7:8080 -> 10.244.1.6:41234 (reply un-DNATed to the VIP)later packets of the sameconnection skip the chains:keep-alive = same pod

Services and ClusterIP: the virtual IP nobody owns Must-know ​

In plain words: a Service is a name plus a stable IP for "whichever pods have these labels and are ready right now". The IP is fake: every node rewrites packets addressed to it into a packet for one real pod.

Common misunderstanding: "If I can ping the ClusterIP, the Service works" (or the reverse). iptables mode only matches the Service's protocol and port; ICMP to the VIP has no rule, so ping fails even when the Service is fine. Test with curl or nc on the port.

Definition: the API server allocates spec.clusterIP from the service CIDR. kube-proxy on every node watches Services and EndpointSlices and installs rules so that a packet to clusterIP:port is DNATed to podIP:targetPort of one ready endpoint. The docs: kube-proxy configures "the node to capture traffic to the Service's clusterIP and port, and redirect that traffic to one of the Service's endpoints". The choice happens once per connection; conntrack remembers it and rewrites the replies back.

text
     netshoot pod (node A)                     node A kernel                          whoami pod (node B)
1    connect 10.96.84.19:80
2                                              OUTPUT/PREROUTING -> KUBE-SERVICES match
3                                              KUBE-SVC-*: random pick -> KUBE-SEP-B
4                                              DNAT dst=10.244.2.7:8080, conntrack entry
5                                              route 10.244.2.0/24 via node B
6                                                                                     SYN from 10.244.1.6 (real source)
7                                                                                     SYN-ACK to 10.244.1.6
8                                              conntrack un-DNAT: src becomes 10.96.84.19:80
9    connected to 10.96.84.19:80 (never sees 10.244.2.7)

Real scenario: a Laravel app connects to redis.cache.svc.cluster.local:6379; Redis restarts with a new pod IP and the app reconnects to the same name and VIP. A Go client with a pooled HTTP/2 connection to a ClusterIP keeps hitting one pod after a scale-up (connection-level balancing). Port mismatch: port: 80 is the VIP's port, targetPort: 8080 is the container's; mixing them up is the most common YAML error.

FieldMeaning
portPort on the ClusterIP (what clients dial)
targetPortPort (number or named port) on the pod
nodePortPort on every node (NodePort/LoadBalancer only)
selectorLabels picking the pods; no selector = you manage EndpointSlices yourself
appProtocolHint for L7 implementations (http, kubernetes.io/h2c, kubernetes.io/ws)
ipFamilyPolicy / ipFamiliesSingle or dual-stack ClusterIPs

How to use it: always dial Service DNS names, never pod IPs or hard-coded ClusterIPs; name your ports (name: http) so targetPort: http survives a container port change. See whoami.yaml.

EndpointSlices, readiness and terminating endpoints Must-know ​

In plain words: an EndpointSlice is the up-to-date list of pod addresses behind a Service, with flags saying which are ready. kube-proxy, CoreDNS (for headless Services) and ingress controllers all read it.

Common misunderstanding: "A running pod receives traffic." A pod receives Service traffic only when its readiness probe passes (the endpoint is ready: true). A pod that is Running but 0/1 READY is in the slice with ready: false and gets nothing.

Definition: the EndpointSlice controller creates slices labelled kubernetes.io/service-name: NAME, "no more than 100 endpoints each" by default (--max-endpoints-per-slice, up to 1000), one slice per address family. Each endpoint carries conditions.ready, serving and terminating (both stable since v1.26), plus nodeName, zone and topology hints. The older Endpoints API is "Deprecated since Kubernetes v1.33": it cannot do dual-stack and truncates long lists.

text
rolling update of whoami, one pod replaced
1  new pod starts, readiness fails          slice: 10.244.2.9 ready=false serving=false
2  readiness passes                          slice: 10.244.2.9 ready=true  -> kube-proxy adds KUBE-SEP
3  old pod gets SIGTERM                      slice: 10.244.1.5 ready=false serving=true terminating=true
4  kube-proxy removes it from new connections (existing ones keep flowing)
5  app drains (preStop sleep / readiness false), exits within terminationGracePeriodSeconds

Real scenario: 502s during every deploy because the app exits on SIGTERM before kube-proxy and the ingress controller have removed it (fix: a short preStop sleep or keep serving for a few seconds, as the Go whoami does); a Service with a typo in its selector has no endpoints at all; a StatefulSet uses publishNotReadyAddresses: true so peers can find each other before they are ready.

ConsumerReads EndpointSlices for
kube-proxy / CiliumProgramming DNAT targets per node
CoreDNSA/AAAA/SRV answers for headless Services
ingress-nginx, Envoy Gateway, TraefikSending directly to pod IPs (they bypass the ClusterIP)
kubectl get endpointslices -l kubernetes.io/service-name=whoamiYou, debugging

How to use it: when a Service "does not work", first run kubectl get endpointslices -l kubernetes.io/service-name=NAME -o wide; empty means selector/labels/readiness, not networking.

kube-proxy modes: iptables, nftables, IPVS and eBPF replacements Must-know ​

In plain words: kube-proxy is a controller on every node that turns Services into kernel packet-rewriting rules. The mode decides which kernel feature holds the rules.

Common misunderstanding: "kube-proxy is a proxy that packets pass through." Not since the old userspace mode was removed: in all current modes kube-proxy only writes rules; the kernel (or eBPF) moves the packets. If kube-proxy crashes, existing rules keep working; only changes stop.

Definition: quoted from the Virtual IPs page. iptables: "For each endpoint, it installs iptables rules which, by default, select a backend Pod at random." nftables: "The nftables API is the successor to the iptables API and is designed to provide better performance and scalability than iptables"; "requires kernel 5.13 or later". IPVS: "The ipvs proxy mode is deprecated" because "the kernel IPVS API turned out to be a bad match for the Kubernetes Services API". In iptables mode the rule count grows with Services × endpoints, and minSyncPeriod (default 1s) batches updates; "Since Kubernetes v1.28, the iptables mode of kube-proxy uses a more minimal approach, only making updates where Services or EndpointSlices have actually changed."

text
iptables chains for Service lab/whoami:http (ClusterIP 10.96.84.19, 3 endpoints)
1  KUBE-SERVICES      -d 10.96.84.19/32 -p tcp --dport 80 -j KUBE-SVC-AAAA
2  KUBE-SVC-AAAA      ! -s 10.244.0.0/16 -d 10.96.84.19/32 ... -j KUBE-MARK-MASQ
3  KUBE-SVC-AAAA      -m statistic --mode random --probability 0.33333 -j KUBE-SEP-1
4  KUBE-SVC-AAAA      -m statistic --mode random --probability 0.50000 -j KUBE-SEP-2
5  KUBE-SVC-AAAA      -j KUBE-SEP-3
6  KUBE-SEP-n         -s <own pod IP> -j KUBE-MARK-MASQ    (hairpin: pod calls itself via the VIP)
7  KUBE-SEP-n         -p tcp -j DNAT --to-destination 10.244.x.y:8080
8  KUBE-POSTROUTING   marked packets -> MASQUERADE

The probabilities chain: 1/3, then 1/2 of the remaining 2/3, then the rest, so each endpoint gets one third. A real iptables-save excerpt from the Kubernetes docs is in Mechanics.

Mode / productLookup costUpdate costBalancingStatus (v1.37)
kube-proxy iptablesLinear in Services for the first matchPartial since v1.28Random, or ClientIP affinityDefault
kube-proxy nftablesVerdict maps (hash lookup)IncrementalRandomStable; "a future version of Kubernetes will change the default to nftables"
kube-proxy ipvsHash tableFastrr, wrr, lc, wlc, lblc, lblcr, sh, dh, sed, nq, mhDeprecated v1.35, removal v1.43
Cilium kube-proxy replacementeBPF hash maps; socket-LB rewrites at connect()Map updatesRandom or Maglev; DSR optionCilium feature (kubeProxyReplacement=true)
Calico eBPF dataplaneeBPFMap updatesRandomCalico option, replaces kube-proxy

nftables mode differs in ways that bite on migration: NodePorts default to --nodeport-addresses primary (not every local IP), it does not add firewall-accept rules for NodePorts, localhost NodePorts need a feature gate, and it does not install the iptables mode's conntrack workaround (--conntrack-tcp-be-liberal restores it).

How to use it: set the mode explicitly (mode: nftables in the KubeProxyConfiguration, kubeProxyMode in kind) so an upgrade does not change it underneath you; leave minSyncPeriod at its default unless sync_proxy_rules_duration_seconds says otherwise; plan IPVS clusters' migration now.

Session affinity Good to know ​

In plain words: "send the same client IP to the same pod" for a while.

Common misunderstanding: "This gives me sticky sessions for my users." It keys on the source IP the node sees, which behind a NAT, an ingress controller or a mesh is the same for thousands of users. It also does nothing for traffic arriving through an L7 proxy that talks to pods directly.

Definition: .spec.sessionAffinity: ClientIP (default None) with .spec.sessionAffinityConfig.clientIP.timeoutSeconds ("the default value is 10800, which works out to be 3 hours"). In iptables mode it uses the recent match; in nftables/IPVS the equivalent.

text
1  client 10.244.1.6 -> VIP  => pod B (recorded)
2  client 10.244.1.6 -> VIP  => pod B (within 3 h)
3  ingress pod 10.244.0.9 forwards ALL users -> VIP => every user lands on one pod

Real scenario: a legacy PHP app with file-based sessions; WebSocket fallbacks (long polling) that need the same backend. Prefer moving session state to Redis (Laravel SESSION_DRIVER=redis) over relying on affinity.

WhereSticky by
Service sessionAffinity: ClientIPSource IP, L4, per node
ingress-nginx affinity: cookie annotationCookie, L7
Gateway APIImplementation-specific (session persistence is an extended feature)
CiliumClientIP affinity supported in kube-proxy replacement

How to use it: only for in-cluster clients with stable IPs; for users, use cookie affinity at the L7 proxy or, better, stateless pods.

Headless Services and per-pod DNS Important ​

In plain words: a Service with clusterIP: None gets no virtual IP; its DNS name returns the IPs of all ready pods, so the client chooses.

Common misunderstanding: "Headless means no load balancing, so it is worse." It moves balancing into the client: gRPC clients with round_robin, database drivers that need to know every replica, Kafka/Cassandra/etcd peers. The cost is that clients must re-resolve, which is exactly the problem the VIP solves.

Definition: the DNS docs: headless Services resolve "to the set of IPs of all of the Pods selected by the Service". With named ports, SRV records _http._tcp.NAME.NS.svc.cluster.local carry ports. With a StatefulSet (serviceName: NAME) each pod also gets a stable name POD.NAME.NS.svc.cluster.local (pod hostname + subdomain). kube-proxy installs nothing for headless Services.

text
dig +short whoami-headless.lab.svc.cluster.local
1  10.244.1.5
2  10.244.2.7
3  10.244.2.8       (order rotates; only ready pods unless publishNotReadyAddresses)
client: connect to each, or pick one per request, re-resolve every N seconds

Real scenario: a gRPC service where a ClusterIP pins every client to one pod; a "clear cache on every replica" admin command (Go client, Laravel command); Postgres with Patroni exposing postgres-0.postgres.db.svc.cluster.local for the primary.

ClientRe-resolves headless names?
Go net/httpPer new connection; idle pooled connections stay on old pods
gRPC-Go dns:/// resolver + round_robinYes, periodically and on connection failure
PHP-FPM / LaravelPer request (new process state), so yes
JVMCaches per networkaddress.cache.ttl

How to use it: use headless + client-side balancing for long-lived multiplexed connections (gRPC, HTTP/2) or peer discovery; set publishNotReadyAddresses: true only for cluster-forming stateful apps.

ExternalName Good to know ​

In plain words: a Service that is only a DNS alias to an outside name.

Common misunderstanding: "It proxies to the external host." The docs: the cluster DNS returns "a CNAME record with that external hostname value. No proxying of any kind is set up." Ports in the spec are ignored; TLS SNI and HTTP Host still carry the alias name unless the client overrides them, which breaks virtual-hosted endpoints.

Definition: type: ExternalName, externalName: db.prod.example.com. No ClusterIP, no EndpointSlice, no kube-proxy rules.

text
1  app resolves orders-db.shop.svc.cluster.local
2  CoreDNS: CNAME db.prod.example.com -> A 10.20.30.40
3  app connects to 10.20.30.40 directly; Host/SNI header = orders-db.shop.svc.cluster.local (!)

Real scenario: migrating a managed database into or out of the cluster without changing app config; pointing dev namespaces at a shared staging service.

WantUse
DNS alias to a hostnameExternalName
Stable in-cluster VIP to fixed external IPsService without selector + a manual EndpointSlice
Real proxying with TLS originationAn egress gateway (Istio) or a small proxy Deployment

How to use it: fine for TCP protocols that ignore the name (Postgres, Redis); for HTTPS, make the client send the real hostname.

NodePort Must-know ​

In plain words: the same high port opened on every node, forwarding into the Service.

Common misunderstanding: "NodePort only works on the node where the pod runs." It works on every node (with the default externalTrafficPolicy: Cluster): the receiving node forwards to a pod elsewhere, and SNATs the packet to its own IP so the reply comes back through it.

Definition: the control plane allocates from --service-node-port-range "(default: 30000-32767)". Each node "proxies that port (the same port number on every Node) into your Service". A NodePort Service is also a ClusterIP Service. The Source IP tutorial: for NodePort the node replaces the source address with its own (SNAT) and the destination with the pod IP (DNAT).

text
client 198.51.100.23 -> node1 172.18.0.3:30080, pod only on node2
1  node1 PREROUTING: KUBE-NODEPORTS dport 30080 -> KUBE-EXT-* -> KUBE-MARK-MASQ -> KUBE-SVC-*
2  node1 DNAT -> 10.244.2.7:8080, POSTROUTING MASQUERADE src -> 172.18.0.3 (or node1's pod-net gw IP)
3  pod sees RemoteAddr = node1's address, not 198.51.100.23
4  reply -> node1 -> conntrack reverses both -> client

Real scenario: an on-prem cluster behind an F5 or HAProxy pointing at node:3xxxx; kind exposing a service on localhost through extraPortMappings; a cloud security group that does not open 30000-32767 makes NodePorts "time out" from outside while working from inside.

KnobEffect
nodePort: 30080Fixed port instead of random
--nodeport-addresses (kube-proxy)Which node IPs listen; nftables default primary
externalTrafficPolicy: LocalNo SNAT, only nodes with local pods answer
Firewall / security groupMust allow the NodePort range from the load balancer

How to use it: as the plumbing underneath LoadBalancer and for bare-metal LBs; avoid giving users node:30080 URLs.

LoadBalancer, cloud controllers and MetalLB Must-know ​

In plain words: type: LoadBalancer asks "something" to create an external load balancer and write its address into the Service. Without that something, the Service waits forever.

Common misunderstanding: "EXTERNAL-IP <pending> is a networking problem." It means no controller has handled the Service: no cloud controller (kind, bare metal, minikube without tunnel), wrong loadBalancerClass, or the controller is failing (check its logs and the Service's events).

Definition: "The actual creation of the load balancer happens asynchronously, and information about the provisioned balancer is published in the Service's .status.loadBalancer field." A LoadBalancer Service is also a NodePort Service unless allocateLoadBalancerNodePorts: false (for LBs that send straight to pod IPs). loadBalancerClass selects a non-default implementation.

text
1  kubectl apply Service type=LoadBalancer         status.loadBalancer: {}   EXTERNAL-IP <pending>
2  controller sees it, calls cloud API / announces IP
3  status.loadBalancer.ingress[0].ip = 203.0.113.10
4  LB health-checks nodes (NodePort or healthCheckNodePort) or pods (IP targets)
5  client -> 203.0.113.10:80 -> node:NodePort or pod:8080

Real scenario: EKS with the AWS Load Balancer Controller creating an NLB with IP targets; MetalLB in a data centre giving 192.168.10.240; kind with Cloud Provider KIND, which "runs as a standalone binary in your host ... and provisions new Load Balancer containers for your Services".

ImplementationHow the IP reaches the clusterTargets
AWS Load Balancer ControllerProvisions NLBs for Services, ALBs for Ingress, both for Gateway APIInstance (NodePort) or IP (pod) mode
GKEGoogle Cloud load balancers created by GKE's controllersSee the GKE load-balancing docs
Azure cloud providerAzure Load BalancerNodes
MetalLBLayer 2: "one machine in the cluster takes ownership of the service" via ARP/NDP; or BGP to routersNodes
Cilium LB IPAM + L2/BGPCilium announces Service IPseBPF on nodes
Cloud Provider KINDAn Envoy container per Service on the Docker networkkind nodes

How to use it: on bare metal install MetalLB (or Cilium LB IPAM) before creating LoadBalancer Services; in clouds prefer IP-target modes to remove the NodePort hop; for HTTP, one LoadBalancer for the Gateway/Ingress controller instead of one per Service.

Client198.51.100.23type: LoadBalancercloud LB / MetalLBVIP 203.0.113.10:80health: healthCheckNodePort(Local policy only)node1 :31555 (NodePort)no local podCluster: SNAT to node1,DNAT to pod on node2Local: drop, health check failsnode2 :31555 (NodePort)has a ready podCluster: may still SNATLocal: DNAT only,source keptPod 10.244.2.7:8080Cluster: RemoteAddr= node IP (10.244.x.1 / node)Local: RemoteAddr= 198.51.100.23extra hop,Cluster policy onlyTrade-offCluster: even spread,client IP lostLocal: IP kept, uneven

Traffic policies: externalTrafficPolicy and internalTrafficPolicy Must-know ​

In plain words: "may this node forward to pods on other nodes?" Cluster says yes (even spread, client IP lost); Local says only to pods on this node (client IP kept, uneven spread, nodes without pods drop).

Common misunderstanding: "Local is free." With 3 nodes and pods on 2 of them, the third node black-holes its share unless the load balancer health-checks it out; with 1 pod on node A and 5 on node B, node A's one pod gets as much traffic as node B's five together.

Definition: Source IP tutorial: with externalTrafficPolicy: Local, "kube-proxy only proxies proxy requests to local endpoints, and does not forward traffic to other nodes. This approach preserves the original source IP address. If there are no local endpoints, packets sent to the node are dropped". For LoadBalancer Services Kubernetes allocates spec.healthCheckNodePort, which returns 200 only on nodes with local ready endpoints, so cloud LBs skip empty nodes. internalTrafficPolicy: Local: "only node local endpoints are considered" for in-cluster traffic (no fallback: no local pod means no connection). With ProxyTerminatingEndpoints (stable since v1.28) a node whose local pods are all terminating keeps serving through them while the LB drains it.

text
externalTrafficPolicy: Cluster                externalTrafficPolicy: Local
1  LB -> node1 (no pod)                      1  LB health check node1 -> 503, node1 removed
2  node1 SNAT+DNAT -> pod on node2            2  LB -> node2 (has pod)
3  pod sees node1's IP                        3  node2 DNAT only -> local pod
                                              4  pod sees 198.51.100.23

Real scenario: rate limiting and geo-IP in Laravel see every request from 10.244.x.x; an audit log full of node IPs; a node-local DaemonSet (log agent, NodeLocal DNSCache) reached through a Service with internalTrafficPolicy: Local.

SettingClient IP seenBalanceFailure mode
externalTrafficPolicy: Cluster (default)Node IP (SNAT)Even across podsExtra hop
externalTrafficPolicy: LocalReal clientPer node, not per podDrops on pod-less nodes without LB health checks
internalTrafficPolicy: Cluster (default)Real pod IPEven
internalTrafficPolicy: LocalReal pod IPNode-local onlyNo local pod = connection fails
L7 proxy + X-Forwarded-ForHeader, if trustedProxy's choiceSpoofing if every hop is trusted
PROXY protocol on LBHeader at L4LB'sApp/ingress must speak it

How to use it: for HTTP, run the ingress/gateway pods with Local (often as a DaemonSet or with anti-affinity) and let the app read X-Forwarded-For through Laravel TrustProxies; for raw TCP, Local or PROXY protocol. Lab step 8 shows both behaviours.

Topology-aware routing and trafficDistribution Good to know ​

In plain words: "prefer a pod in my zone (or on my node)" to cut cross-zone latency and cloud data-transfer cost.

Common misunderstanding: "Turning it on always keeps traffic local." The annotation-based heuristic (service.kubernetes.io/topology-mode: Auto) only kicks in when endpoints can be spread proportionally; the docs warn that with "fewer than 3 endpoints per zone, there is a high (≈50%) probability" it falls back to cluster-wide routing. It can also overload one zone when traffic is not evenly sourced.

Definition: the EndpointSlice controller writes hints.forZones (and forNodes) into slices; kube-proxy filters endpoints by its own zone. The newer field spec.trafficDistribution takes PreferSameZone (traffic stays in-zone if any endpoint is there, else cluster-wide), PreferSameNode (node, then zone, then cluster), and PreferClose as a deprecated alias of PreferSameZone. Hints are ignored when internalTrafficPolicy: Local is set.

text
zone a: client pod; endpoints a1, a2       zone b: b1, b2, b3
trafficDistribution: PreferSameZone
1  kube-proxy on the client's node keeps only hints for zone a -> a1 or a2
2  a1 and a2 become unready -> no zone-a endpoints -> falls back to b1..b3

Real scenario: a three-zone EKS cluster paying for cross-AZ traffic between an API and its cache; a node-local cache Service with PreferSameNode.

MechanismGranularityFallback
topology-mode: Auto annotationZone, proportionalCluster-wide when allocation is unsafe
trafficDistribution: PreferSameZoneZoneCluster-wide
trafficDistribution: PreferSameNodeNodeZone, then cluster
internalTrafficPolicy: LocalNode, strictNone

How to use it: use trafficDistribution: PreferSameZone for chatty in-cluster calls with replicas in every zone, watch per-pod load, and keep enough replicas per zone.

Cluster DNS: CoreDNS, records, ndots:5 Must-know ​

In plain words: every pod's /etc/resolv.conf points at the cluster DNS Service (CoreDNS), with a search list so whoami and whoami.lab work as short names. The price is that external names are first tried with every cluster suffix.

Common misunderstanding: "api.stripe.com is one DNS query." With the default options ndots:5, any name with fewer than five dots is first tried as a relative name against each search domain. A pod in namespace lab resolving api.stripe.com asks for api.stripe.com.lab.svc.cluster.local, api.stripe.com.svc.cluster.local, api.stripe.com.cluster.local and only then api.stripe.com, each for A and AAAA: up to eight queries, six of them guaranteed NXDOMAIN.

Definition: the kubelet writes the pod's resolver config from --cluster-dns and --cluster-domain; the DNS page shows it: nameserver 10.32.0.10, search <namespace>.svc.cluster.local svc.cluster.local cluster.local, options ndots:5. Records (from DNS for Services and Pods):

NameAnswer
SVC.NS.svc.cluster.local A/AAAAThe ClusterIP (normal Service) or all ready pod IPs (headless)
_PORTNAME._PROTO.SVC.NS.svc.cluster.local SRVPort and target for named ports
POD-HOSTNAME.SUBDOMAIN.NS.svc.cluster.localPod IP (StatefulSet / hostname + subdomain)
ExternalName ServiceCNAME to the external name
Anything not in cluster.localForwarded upstream (forward . /etc/resolv.conf)

dnsPolicy per pod: ClusterFirst (the default; the docs warn that Default "is not the default DNS policy"), Default (inherit the node's resolver), ClusterFirstWithHostNet (needed for hostNetwork pods, otherwise they fall back to Default), and None (supply everything in dnsConfig, including options: [{name: ndots, value: "2"}]).

text
real capture (Docker container with the same resolv.conf, musl resolver, see Mechanics)
1  AAAA? api.stripe.com.lab.svc.cluster.local.   NXDomain
2  AAAA? api.stripe.com.svc.cluster.local.       NXDomain
3  AAAA? api.stripe.com.cluster.local.           NXDomain
4  AAAA? api.stripe.com.                          0 answers
5  A?    api.stripe.com.lab.svc.cluster.local.   NXDomain
6  A?    api.stripe.com.svc.cluster.local.       NXDomain
7  A?    api.stripe.com.cluster.local.           NXDomain
8  A?    api.stripe.com.                          3 answers
with a trailing dot (api.stripe.com.): only steps 4 and 8

The default Corefile, as the DNS debugging page shows it (with log added for debugging):

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

Real scenario: p99 latency of outbound HTTP calls jumps because every new connection pays four NXDOMAIN round trips; CoreDNS CPU is dominated by NXDOMAIN for *.cluster.local suffixes; intermittent 5-second DNS delays from UDP conntrack races on the node (the reason NodeLocal DNSCache exists: "Skipping iptables DNAT and connection tracking will help reduce conntrack races and avoid UDP DNS entries filling up conntrack table"); a NetworkPolicy default-deny that forgot port 53.

FixEffectCost
Use FQDNs with a trailing dot (api.stripe.com.)One query per typeSome libraries reject trailing dots in TLS/Host
dnsConfig.options ndots: "2"api.stripe.com tried absolute firstShort cluster names with 2+ dots behave differently
Full Service names (redis.cache.svc.cluster.local)Fewer misses (4 dots still < 5: one search miss first)Longer config
NodeLocal DNSCache (a link-local IP from 169.254.0.0/16)Per-node cache, TCP upstream, no DNAT/conntrack for DNSOne more DaemonSet
Connection pooling in the appFewer lookups at allMust handle endpoint changes
CoreDNS autopath plugin (with pods verified)Server walks the search pathMore CoreDNS memory and API load

How to use it: keep ClusterFirst, use full Service names in config, add trailing dots or lower ndots for hot external hostnames, and debug from inside a pod (kubectl exec -it netshoot -- dig whoami.lab.svc.cluster.local), never from your laptop. The generic resolver mechanics are in DNS resolution for developers; the Go ndots tool prints the exact query list for any resolv.conf.

Ingress (networking.k8s.io/v1, frozen)IngressClass "nginx"controller: k8s.io/ingress-nginxIngress (one object, one owner)host + path rules, tls secretNameannotations: rewrite, canary, timeouts,auth, CORS, body size ... controller-specific(not portable between controllers)HTTP/HTTPS onlyingressClassNameService webService apiWho edits it: whoever owns the app,but TLS, ports and LB settings live in it tooGateway API (gateway.networking.k8s.io)GatewayClasscontrollerName (implementation)Infra providerGateway (ns gateway-infra)listeners: :80, :443 + TLS certallowedRoutes: which namespacesCluster operatorHTTPRoute (ns shop)parentRefs: Gatewaymatch path/header/querybackendRefs + weightGRPCRoute (ns api)match service/method(TLSRoute, TCPRoute,UDPRoute: experimental)Service v1weight 90Service v2weight 10Service grpcApp developers own Routes; ReferenceGrant allows cross-namespace refs

Ingress Must-know ​

In plain words: one object with host and path rules that an ingress controller (a reverse proxy running in the cluster) turns into its own configuration.

Common misunderstanding: "Creating an Ingress exposes my app." The Ingress object does nothing without a controller watching its ingressClassName; the controller's own Service (usually type: LoadBalancer) is what is exposed. And most real behaviour (rewrites, timeouts, body size, canaries, auth) lives in controller-specific annotations that do not port to another controller.

Definition: "Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster." Rules match host (exact or wildcard *.foo.com) and path with pathType Exact, Prefix (path-element based: /aaa/bbb matches /aaa/bbb/ccc but not /aaa/bbbxyz) or ImplementationSpecific; the longest path wins, Exact beats Prefix on ties. tls lists hosts and a secretName. defaultBackend catches the rest. IngressClass (with annotation ingressclass.kubernetes.io/is-default-class) binds Ingresses to a controller. Status: "The Ingress API has been frozen ... no further changes or updates", and Kubernetes "has no plans to remove Ingress".

text
GET https://shop.example.com/api/orders
1  DNS shop.example.com -> LB 203.0.113.10 (ingress controller's LoadBalancer Service)
2  LB -> node:NodePort or controller pod (TLS terminated in the controller)
3  controller matches host shop.example.com, path Prefix /api -> Service api:80
4  controller reads EndpointSlices, proxies to pod 10.244.2.7:8080 (bypasses the ClusterIP)
5  adds X-Forwarded-For: <client>, X-Forwarded-Proto: https, X-Forwarded-Host

Real scenario: a team copies nginx.ingress.kubernetes.io/rewrite-target annotations from Stack Overflow and breaks every path; moving from ingress-nginx to Traefik means rewriting 40 annotations; a 413 because proxy-body-size defaults to 1m in ingress-nginx; the retirement of Ingress NGINX in March 2026 forces a migration plan.

ControllerConfig surfaceStatus / notes
ingress-nginx (kubernetes/ingress-nginx)Annotations + ConfigMapRetired March 2026: no releases or security fixes; existing installs keep running
NGINX Ingress Controller (F5 NGINX)Annotations + its own CRDsSeparate project; also ships NGINX Gateway Fabric
TraefikAnnotations, IngressRoute CRDs, Gateway APIAlso a Gateway API implementation
HAProxy Ingress / HAProxy Kubernetes IngressAnnotationsDifferent projects with similar names
AWS Load Balancer ControllerAnnotations → ALBIngress "by provisioning Application Load Balancers"
GKE IngressAnnotations, BackendConfig"Kubernetes as a project supports and maintains AWS, and GCE ingress controllers"
Contour, Emissary, Kong, IstioAnnotations / CRDsMost now prefer Gateway API

How to use it: existing Ingresses keep working; for new work, use Gateway API; whichever you use, configure the app to trust only the controller's addresses for X-Forwarded-* (Laravel).

The manifest: the same host routing as the lab's Gateway, written as an Ingress for ingress-nginx (TLS secret, pathType: Prefix, one controller-specific annotation).

yaml
# The same routing as an Ingress. Weighted canaries are not part of the
# Ingress spec; ingress-nginx does them with a second Ingress and
# nginx.ingress.kubernetes.io/canary annotations.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: whoami
  namespace: lab
  annotations:
    nginx.ingress.kubernetes.io/proxy-body-size: "8m"
spec:
  ingressClassName: nginx
  tls:
    - hosts: ["whoami.example.test"]
      secretName: whoami-tls
  rules:
    - host: whoami.example.test
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: whoami
                port: { number: 80 }

Gateway API Must-know ​

In plain words: Ingress split into role-sized pieces with typed fields: the platform team owns the Gateway (ports, TLS, which namespaces may attach), app teams own Routes that attach to it.

Common misunderstanding: "Gateway API is a new proxy." It is only an API (CRDs); you still install an implementation (Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, Traefik, Kong, cloud controllers), and features are graded by conformance (core, extended, implementation-specific).

Definition: the Kubernetes page lists design principles "Role-oriented", "Portable", "Expressive" ("header-based matching, traffic weighting, and others that were only possible in Ingress by using custom annotations") and "Extensible", and the roles Infrastructure Provider, Cluster Operator, Application Developer. Stable kinds: GatewayClass (controllerName of the implementation), Gateway (listeners: protocol, port, hostname, TLS, allowedRoutes), HTTPRoute (matches on path, headers, query, method; filters for redirects, rewrites, header changes, mirroring; backendRefs with weight), GRPCRoute (service/method matches). ReferenceGrant allows cross-namespace references; TLSRoute, TCPRoute, UDPRoute are in the experimental channel. Weights are proportional: "the sum of all the weights within a single route rule is the denominator".

text
GatewayClass eg (controllerName gateway.envoyproxy.io/gatewayclass-controller)   <- installed by platform
Gateway web, listener http :80, allowedRoutes: Same namespace                    <- cluster operator
HTTPRoute whoami: host whoami.example.test, / -> whoami:80 weight 90, whoami-v2:80 weight 10   <- app team
1  implementation provisions an Envoy Deployment + LoadBalancer Service for Gateway web
2  route status: Accepted=True, ResolvedRefs=True (or a reason such as NotAllowedByListeners)
3  ~10% of requests land on v2; change weights to 50/50, then 0/100 to finish

Real scenario: canary releases without annotation hacks; a shared company Gateway with TLS managed by the platform team while 30 teams attach HTTPRoutes; gRPC services routed by method; Laravel Octane behind an HTTPRoute (laravel.yaml).

ConcernIngressGateway API
OwnershipOne object mixes LB, TLS and routesGatewayClass / Gateway / Route per role
ProtocolsHTTP(S)HTTP, gRPC (stable); TLS, TCP, UDP (experimental)
Canary / weightsController annotationsbackendRefs[].weight
Header / method / query matchingAnnotationsTyped match fields
Cross-namespaceNot definedRoutes attach across namespaces; ReferenceGrant for backends
Statusstatus.loadBalancer onlyPer-route conditions (Accepted, ResolvedRefs)
API stateFrozenActively developed (gateway-api.sigs.k8s.io)

How to use it: install one implementation per cluster (lab uses Envoy Gateway v1.10.0), give app namespaces allowedRoutes, write one HTTPRoute per app; migrate Ingresses with the project's "Migrating from Ingress" / "Migrating from Ingress-NGINX" guides.

The manifests: GatewayClass, Gateway and the 90/10 HTTPRoute, plus the canary Deployment and Service.

yaml
# Gateway API: the platform team owns GatewayClass + Gateway,
# the app team owns the HTTPRoute that attaches to it.
# controllerName below is Envoy Gateway's (from its v1.10.0 quickstart.yaml);
# other implementations publish their own.
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: eg
spec:
  controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web
  namespace: lab
spec:
  gatewayClassName: eg
  listeners:
    - name: http
      protocol: HTTP
      port: 80
      allowedRoutes:
        namespaces: { from: Same }
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: whoami
  namespace: lab
spec:
  parentRefs:
    - name: web
  hostnames: ["whoami.example.test"]
  rules:
    - matches:
        - path: { type: PathPrefix, value: / }
      backendRefs:
        - { name: whoami, port: 80, weight: 90 }
        - { name: whoami-v2, port: 80, weight: 10 }
yaml
# Canary: its own label (app: whoami-v2) and its own Service so a
# Gateway API HTTPRoute can split traffic by weight between the two.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: whoami-v2
  namespace: lab
spec:
  replicas: 1
  selector:
    matchLabels: { app: whoami-v2 }
  template:
    metadata:
      labels: { app: whoami-v2 }
    spec:
      containers:
        - name: whoami
          image: academy/whoami:v1
          imagePullPolicy: IfNotPresent
          ports:
            - { name: http, containerPort: 8080 }
          env:
            - { name: VERSION, value: v2 }
          readinessProbe:
            httpGet: { path: /readyz, port: http }
---
apiVersion: v1
kind: Service
metadata:
  name: whoami-v2
  namespace: lab
spec:
  selector: { app: whoami-v2 }
  ports:
    - { name: http, port: 80, targetPort: http }

NetworkPolicy Must-know ​

In plain words: label-based firewall rules for pods. By default everything may talk to everything; the first policy that selects a pod for a direction turns that direction into "deny unless allowed".

Common misunderstanding: "I created a NetworkPolicy, so traffic is restricted." Only if the CNI enforces it: "Your cluster must use a network plugin that supports NetworkPolicy enforcement." flannel alone ignores policies silently. Second misunderstanding: "default deny egress is safe": "A default deny-all egress policy also blocks DNS traffic."

Definition: "By default, a pod is non-isolated for egress; all outbound connections are allowed. A pod is isolated for egress if there is any NetworkPolicy that both selects the pod and has "Egress" in its policyTypes" (same for ingress). Rules are allow-lists, additive across policies. Peers: podSelector (same namespace), namespaceSelector (use the immutable kubernetes.io/metadata.name label to pick by name), both combined in one element (AND) or as two elements (OR), and ipBlock with except. Ports with protocol, port, endPort. Exceptions: "a pod cannot block access to itself" and "traffic to and from the node where a Pod is running is always allowed". A connection needs both the client's egress and the server's ingress to allow it; replies are allowed automatically (stateful).

text
lab namespace after netpol.yaml
1  netshoot -> whoami:8080           egress netshoot-to-whoami OK, ingress whoami-from-netshoot OK -> allowed
2  netshoot -> CoreDNS :53           egress allow-dns OK (kube-system has no policy) -> allowed
3  netshoot -> 1.1.1.1:443           no egress rule -> dropped (curl times out, no RST)
4  whoami  -> whoami (other pod)     no ingress rule for app=whoami from app=whoami -> dropped

Real scenario: PCI scope reduction (only the payments namespace may reach the card vault); a compromised pod cannot scan the cluster; Redis reachable only from the app's web and Horizon pods (laravel.yaml); outage after a "harmless" default-deny because probes still worked (node traffic is allowed) while DNS and the database broke.

CNIKubernetes NetworkPolicyExtras
CalicoYesGlobalNetworkPolicy, ordered policies, deny rules, host endpoints
CiliumYesCiliumNetworkPolicy: L7 rules (HTTP method/path regex, DNS) answered with HTTP 403 / DNS REFUSED, FQDN egress with toFQDNs, identities
AntreaYesTiered ClusterNetworkPolicy
kindnet (recent kind releases)Yes (verify with lab step 9)Basic
flannel aloneNoPair with Calico ("Canal")
AWS VPC CNIYes (network policy agent, eBPF)Security groups for pods
GKE Dataplane V2 / Azure (Cilium-based)YesCilium features vary by provider

AdminNetworkPolicy / BaselineAdminNetworkPolicy (SIG Network, cluster-scoped, deny-capable) is a separate CRD API that some CNIs implement for platform-wide guardrails.

How to use it: per namespace: default deny both directions, allow DNS egress to kube-system/k8s-app: kube-dns on UDP and TCP 53, then allow each real flow on both sides; test with a pod that should be blocked. Lab step 9 does exactly this.

The manifests: default deny, allow DNS, and one flow allowed on both sides.

yaml
# 1) Deny all ingress and egress for every pod in the namespace.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: lab
spec:
  podSelector: {}
  policyTypes: [Ingress, Egress]
---
# 2) Let every pod in the namespace resolve names via CoreDNS.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-dns
  namespace: lab
spec:
  podSelector: {}
  policyTypes: [Egress]
  egress:
    - to:
        - namespaceSelector:
            matchLabels: { kubernetes.io/metadata.name: kube-system }
          podSelector:
            matchLabels: { k8s-app: kube-dns }
      ports:
        - { protocol: UDP, port: 53 }
        - { protocol: TCP, port: 53 }
---
# 3) Let netshoot call whoami on 8080 (both sides must allow it).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: whoami-from-netshoot
  namespace: lab
spec:
  podSelector:
    matchLabels: { app: whoami }
  policyTypes: [Ingress]
  ingress:
    - from:
        - podSelector:
            matchLabels: { app: netshoot }
      ports:
        - { protocol: TCP, port: 8080 }
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: netshoot-to-whoami
  namespace: lab
spec:
  podSelector:
    matchLabels: { app: netshoot }
  policyTypes: [Egress]
  egress:
    - to:
        - podSelector:
            matchLabels: { app: whoami }
      ports:
        - { protocol: TCP, port: 8080 }

Egress: SNAT, egress gateways, NAT gateways and conntrack Important ​

In plain words: pod IPs are private; when a pod calls something outside the cluster the node rewrites the source to its own IP (masquerade). In the cloud a NAT gateway may rewrite it again. Partners who allow-list IPs see the node or NAT gateway, never the pod.

Common misunderstanding: "I can allow-list my pod's IP at the partner." Pod IPs change and are not routable outside the cluster; you must give a stable egress IP (NAT gateway Elastic IP, or an egress gateway node).

Definition: the CNI or kube-proxy installs a masquerade rule for traffic from the pod CIDR to destinations outside the cluster ranges (GKE ip-masq-agent, Calico natOutgoing, Cilium bpf.masquerade/iptables, AWS VPC CNI external SNAT setting). Cilium's Egress Gateway masquerades matching traffic "with selected, predictable IPs associated with the gateway nodes" (CiliumEgressGatewayPolicy); Calico Enterprise, Istio egress gateways and OpenShift egress IPs do the same job. Every flow occupies a conntrack entry on the node (and a port on the NAT gateway).

text
pod 10.244.1.5:51000 -> api.partner.com 198.51.100.80:443   (EKS, private subnet)
1  node: POSTROUTING MASQUERADE src -> 10.0.12.34:51000 (node VPC IP)    conntrack entry #1
2  NAT gateway: SNAT src -> 52.1.2.3:3001 (Elastic IP)                    NAT table entry
3  partner sees 52.1.2.3 -> allow-list that
4  thousands of short connections to one host -> conntrack and NAT-port pressure

Real scenario: a webhook partner allow-lists one IP; nf_conntrack: table full, dropping packet on busy nodes; AWS NAT gateway port allocation errors when hundreds of pods hit one API without keep-alive; egress cost surprises from pulling images through a NAT gateway.

NeedOption
Stable egress IP, cloudPrivate subnets + NAT gateway with Elastic IP / Cloud NAT static IP
Stable egress IP per namespace/appCilium Egress Gateway, Calico egress gateways, Istio egress gateway, OpenShift EgressIP
Restrict where pods may goNetworkPolicy egress (ipBlock), Cilium toFQDNs, a proxy
Fewer conntrack entriesKeep-alive and pooling, NodeLocal DNSCache, raise nf_conntrack_max

How to use it: decide early whether partners need a fixed IP; reuse connections (Go http.Client, Laravel Http with keep-alive in Octane); watch conntrack -S on nodes. NAT tables in general are in NAT and port forwarding.

hostNetwork and hostPort Good to know ​

In plain words: hostNetwork: true puts the pod in the node's network namespace (no pod IP of its own); hostPort keeps the pod network but maps one node port to the pod with a DNAT rule.

Common misunderstanding: "hostPort is like NodePort." It opens the port only on the node where that pod runs, and two pods with the same hostPort cannot share a node (the scheduler enforces it).

Definition: hostNetwork pods see the node's interfaces and must use dnsPolicy: ClusterFirstWithHostNet to keep cluster DNS. hostPort needs the CNI portmap plugin ("specify portMappings capability in your cni-conf-dir").

text
1  hostNetwork pod binds :9100 -> listens on node 172.18.0.3:9100 (and conflicts with anything else there)
2  hostPort: 8443 -> portmap DNAT node:8443 -> pod 10.244.1.5:8443 on that node only

Real scenario: node exporters, CNI agents, kube-proxy itself and some ingress controllers run with hostNetwork; NetworkPolicy does not apply to host-network pods.

OptionOwn IPPort conflictsTypical use
Pod network (default)YesNoneEverything
hostPortYesPer nodeLegacy, edge proxies
hostNetwork: trueNo (node IP)With every host processNode agents, CNI, monitoring

How to use it: avoid both in application workloads; prefer Services.

Dual-stack IPv4/IPv6 Good to know ​

In plain words: pods and Services can have an IPv4 and an IPv6 address at the same time.

Common misunderstanding: "Enabling IPv6 on the cluster makes my existing Services dual-stack." Services default to SingleStack; you opt in per Service.

Definition: all components "must agree on the configured primary IP family". Service fields ipFamilyPolicy (SingleStack, PreferDualStack, RequireDualStack) and ipFamilies ([IPv4, IPv6], order = primary). EndpointSlices are per family. A dual-stack LoadBalancer needs a cloud that supports both. For IPv6-only pods reaching the IPv4 internet you need NAT64/DNS64 or similar.

text
1  Service whoami ipFamilyPolicy: PreferDualStack
2  spec.clusterIPs: [10.96.84.19, fd00:10:96::3a1]
3  two EndpointSlices: addressType IPv4 and IPv6

Real scenario: EKS IPv6 clusters to escape VPC IPv4 exhaustion; partners that only accept IPv4.

PolicyResult
SingleStack (default)One ClusterIP of the primary family
PreferDualStackBoth if the cluster supports it
RequireDualStackBoth or the API rejects the Service

How to use it: listen on :: and 0.0.0.0 (Go's :8080 does both), avoid storing IPs in VARCHAR(15) (see the SQL below).

Service mesh overlap: sidecar REDIRECT and ambient Good to know ​

In plain words: a mesh adds its own proxy into the data path: either a sidecar in every pod that captures traffic with iptables REDIRECT, or (Istio ambient) a per-node ztunnel for L4/mTLS plus optional waypoint proxies for L7.

Common misunderstanding: "The mesh replaces Services." Meshes still use Services and EndpointSlices for discovery; they replace kube-proxy's per-connection random choice with per-request L7 balancing, retries and mTLS.

Definition: Istio sidecar injection adds an init container (or the Istio CNI plugin) that installs nat rules in the pod namespace redirecting outbound TCP to Envoy on 15001 and inbound to 15006. Istio's ambient documentation describes the ambient data plane as node-level ztunnel proxies deployed as a DaemonSet. Istio's application-requirements page lists the ports: 15001 (Envoy outbound), 15006 (Envoy inbound), 15008 (HBONE mTLS tunnel). Linkerd uses a Rust micro-proxy sidecar with the same interception idea; Cilium service mesh uses eBPF plus per-node Envoy.

text
app -> http://orders:80
1  pod netns OUTPUT: nat REDIRECT outbound TCP -> 127.0.0.1:15001 (Envoy outbound)
2  Envoy picks a pod from EndpointSlices, opens mTLS to its sidecar 10.244.2.7:15006
3  server pod PREROUTING: nat REDIRECT inbound -> :15006 (Envoy inbound) -> app :8080

Real scenario: gRPC load balancing fixed by adding a mesh; NetworkPolicies that allow port 8080 but the sidecar talks on 15008 (HBONE in ambient); debugging needs istioctl proxy-config besides iptables-save.

Data pathWho balancesmTLS
Plain Servicekube-proxy, per connectionNo
Sidecar mesh (Istio, Linkerd)Sidecar, per requestYes
Ambient (Istio)ztunnel L4; waypoint L7Yes

How to use it: design choices are in service mesh and the sidecar pattern and API gateway, BFF and service mesh.

kubectl port-forward Important ​

In plain words: a debugging tunnel from your laptop through the API server and the kubelet into one pod's port. It is not a Service and not a network path your users take.

Common misunderstanding: "port-forward svc/whoami tests my Service." It resolves the Service to one pod once and tunnels to it; it skips kube-proxy, NetworkPolicy, ClusterIP rules and readiness changes. So "port-forward works but the Service does not" is a classic sign of selector, port or policy problems.

Definition: kubectl port-forward opens a streaming connection (SPDY or WebSockets) to the API server, which proxies to the kubelet on the pod's node, which connects into the pod's network namespace to localhost:PORT. The docs: it "is implemented for TCP ports only" and "Authorization is enforced by the Kubernetes API server" (RBAC on pods/portforward).

text
laptop:8080 -> kubectl -> HTTPS to API server -> kubelet on node B -> pod netns 127.0.0.1:8080
(no ClusterIP, no iptables, no NetworkPolicy, no readiness on the path)

Real scenario: connecting a local SQL client to a database pod; checking an app port when the Ingress fails; a pod listening on 127.0.0.1 works through port-forward but not through its Service (it must listen on 0.0.0.0).

ToolPathGood for
kubectl port-forwardAPI server tunnel to one podAd-hoc access
kubectl proxyLocal HTTP proxy to the API (and services/proxy)API calls
kubectl exec into netshootReal in-cluster pathTesting Services, DNS, policy
NodePort / extraPortMappingsReal data pathLab exposure

How to use it: for access, not for testing the Service; test Services from a pod inside the cluster.

Mechanics ​

One request, hop by hop ​

A browser hits https://whoami.example.test/ through a Gateway; the route sends it to a pod on another node.

text
     component                         src -> dst after this hop                              who rewrites
1    client                            198.51.100.23:50000 -> 203.0.113.10:443                -
2    cloud LB / MetalLB node           (passthrough) -> nodeX:31443 or gateway pod IP         LB (SNAT unless Local / IP targets)
3    kube-proxy on nodeX               -> 10.244.1.20:10443 (Envoy pod)                       DNAT (+SNAT with Cluster policy)
4    Envoy (Gateway)                   TLS terminated; new connection 10.244.1.20 -> 10.244.2.7:8080   L7 proxy, adds X-Forwarded-For
5    node routing / overlay            10.244.1.20 -> 10.244.2.7 inside VXLAN 172.18.0.3 -> 172.18.0.4    CNI (no NAT)
6    pod veth                          delivered; RemoteAddr = 10.244.1.20, XFF = 198.51.100.23        -
7    pod -> postgres-rw.db (ClusterIP) 10.244.2.7 -> 10.96.0.50:5432 -> DNAT 10.244.3.4:5432          kube-proxy on node B
8    pod -> api.partner.com            10.244.2.7 -> masquerade node B IP -> NAT gateway EIP           node SNAT, cloud NAT

The iptables rules kube-proxy writes ​

The top of the ruleset, as printed in the Kubernetes blog post on nftables mode (Dan Winship, 2025), one rule per Service IP and port:

text
# If the packet is addressed to 172.30.0.41:80, then jump to the chain
# KUBE-SVC-XPGD46QRK7WJZT7O for further processing
-A KUBE-SERVICES -m comment --comment "namespace1/service1:p80 cluster IP" -m tcp -p tcp -d 172.30.0.41 --dport 80 -j KUBE-SVC-XPGD46QRK7WJZT7O

# If the packet is addressed to 172.30.0.42:443, then...
-A KUBE-SERVICES -m comment --comment "namespace2/service2:p443 cluster IP" -m tcp -p tcp -d 172.30.0.42 --dport 443 -j KUBE-SVC-GNZBNJ2PO5MGZ6GT

"This means that when a packet comes in, the time it takes the kernel to check it against all of the Service rules is O(n) in the number of Services." Below that sits one chain per Service and one per endpoint. The Kubernetes Debug Services task prints the full set for a Service hostnames with three endpoints (iptables-save | grep hostnames on a node):

text
-A KUBE-SEP-57KPRZ3JQVENLNBR -s 10.244.3.6/32 -m comment --comment "default/hostnames:" -j MARK --set-xmark 0x00004000/0x00004000
-A KUBE-SEP-57KPRZ3JQVENLNBR -p tcp -m comment --comment "default/hostnames:" -m tcp -j DNAT --to-destination 10.244.3.6:9376
-A KUBE-SEP-WNBA2IHDGP2BOBGZ -s 10.244.1.7/32 -m comment --comment "default/hostnames:" -j MARK --set-xmark 0x00004000/0x00004000
-A KUBE-SEP-WNBA2IHDGP2BOBGZ -p tcp -m comment --comment "default/hostnames:" -m tcp -j DNAT --to-destination 10.244.1.7:9376
-A KUBE-SEP-X3P2623AGDH6CDF3 -s 10.244.2.3/32 -m comment --comment "default/hostnames:" -j MARK --set-xmark 0x00004000/0x00004000
-A KUBE-SEP-X3P2623AGDH6CDF3 -p tcp -m comment --comment "default/hostnames:" -m tcp -j DNAT --to-destination 10.244.2.3:9376
-A KUBE-SERVICES -d 10.0.1.175/32 -p tcp -m comment --comment "default/hostnames: cluster IP" -m tcp --dport 80 -j KUBE-SVC-NWV5X2332I4OT4T3
-A KUBE-SVC-NWV5X2332I4OT4T3 -m comment --comment "default/hostnames:" -m statistic --mode random --probability 0.33332999982 -j KUBE-SEP-WNBA2IHDGP2BOBGZ
-A KUBE-SVC-NWV5X2332I4OT4T3 -m comment --comment "default/hostnames:" -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-X3P2623AGDH6CDF3
-A KUBE-SVC-NWV5X2332I4OT4T3 -m comment --comment "default/hostnames:" -j KUBE-SEP-57KPRZ3JQVENLNBR

Read it bottom-up: each KUBE-SEP-* chain marks hairpin traffic (-s its own pod IP) with 0x4000 and DNATs to its pod; KUBE-SVC-* picks one endpoint with -m statistic --mode random --probability (0.333, then 0.5, then the rest); KUBE-SERVICES matches the ClusterIP and port. Not in this excerpt but present on every node: NodePort Services add KUBE-NODEPORTS → KUBE-EXT-* rules, KUBE-MARK-MASQ sets the same 0x4000 mark, and KUBE-POSTROUTING masquerades marked packets. The docs' rule of thumb: "For each port of each Service, there should be 1 rule in KUBE-SERVICES and one KUBE-SVC-<hash> chain." A Service with no ready endpoints gets a REJECT in the filter table's KUBE-SERVICES chain instead, which is why curl fails instantly rather than timing out. Lab step 4 prints the same structure for lab/whoami.

What nftables mode looks like ​

The same blog post shows the replacement: one rule and a verdict map, so a lookup is one hash probe regardless of the number of Services.

text
table ip kube-proxy {
	map service-ips {
		type ipv4_addr . inet_proto . inet_service : verdict
		comment "ClusterIP, ExternalIP and LoadBalancer IP traffic"
		elements = { 172.30.0.41 . tcp . 80 : goto service-ULMVA6XW-namespace1/service1/tcp/p80,
                             172.30.0.42 . tcp . 443 : goto service-42NFTM6N-namespace2/service2/tcp/p443,
                             ... }
        }
	chain services {
		ip daddr . meta l4proto . th dport vmap @service-ips
	}
}

Inspect it on a node with nft list table ip kube-proxy. The post's motivation in one line: the iptables API "was designed for implementing simple firewalls, and has problems scaling up to support Service proxying in a large Kubernetes cluster with tens of thousands of Services."

Bytes on the wire: a pod's DNS query ​

Real capture (tcpdump -X) of the first query in the ndots sequence above, from a container with a Kubernetes-style resolv.conf:

text
17:58:33.528265 IP 172.17.0.11.44885 > 1.1.1.1.53: 30358+ AAAA? api.stripe.com.lab.svc.cluster.local. (54)
	0x0000:  4500 0052 a33d 4000 4011 e93f ac11 000b  E..R.=@.@..?....
	0x0010:  0101 0101 af55 0035 003e ae6d 7696 0100  .....U.5.>.mv...
	0x0020:  0001 0000 0000 0000 0361 7069 0673 7472  .........api.str
	0x0030:  6970 6503 636f 6d03 6c61 6203 7376 6307  ipe.com.lab.svc.
	0x0040:  636c 7573 7465 7205 6c6f 6361 6c00 001c  cluster.local...
	0x0050:  0001                                     ..
BytesMeaning
4500 0052IPv4, header 20 bytes, total length 0x52 = 82
4011TTL 64, protocol 17 (UDP)
ac11 000b → 0101 0101172.17.0.11 → 1.1.1.1 (in a pod: pod IP → CoreDNS ClusterIP, DNATed to a CoreDNS pod)
af55 0035Source port 44885 → destination port 53
003eUDP length 62
7696 0100DNS ID 0x7696 (30358), flags 0x0100 = standard query, recursion desired
0001 0000 0000 00001 question, 0 answers, 0 authority, 0 additional
03 617069 06 737472697065 03 636f6d 03 6c6162 03 737663 07 636c7573746572 05 6c6f63616c 00Length-prefixed labels api.stripe.com.lab.svc.cluster.local.
001c 0001QTYPE 28 (AAAA), QCLASS 1 (IN)

Every one of those NXDOMAIN questions is a UDP flow that kube-proxy DNATs and conntrack tracks on the node, which is where the conntrack races that NodeLocal DNSCache avoids come from.

Knobs and where they live ​

KnobComponentDefaultEffect
--cluster-cidrkube-controller-manager / CNIkind 10.244.0.0/16Pod address space
--service-cluster-ip-rangekube-apiserverkind 10.96.0.0/16ClusterIP space
--service-node-port-rangekube-apiserver30000-32767NodePort range
modekube-proxy configiptables (Linux)Proxy backend
iptables.minSyncPeriod / syncPeriodkube-proxy1s / 30sRule batching
--nodeport-addresseskube-proxyall (iptables), primary (nftables)Which IPs serve NodePorts
conntrack.maxPerCore, tcpEstablishedTimeoutkube-proxy32768, 24hSets nf_conntrack_max and timeouts on the node
--max-endpoints-per-slicekube-controller-manager100 (max 1000)Slice size
clusterDNS, clusterDomainkubelet10.96.0.10, cluster.localPod resolv.conf
dnsPolicy, dnsConfigPod specClusterFirstPer-pod DNS
sessionAffinityConfig.clientIP.timeoutSecondsService10800Affinity duration
Corefile cache 30, forward, autopathCoreDNS ConfigMapas shown aboveDNS behaviour
CNI MTUCNI configplugin-specific (1450 VXLAN)Pod eth0 MTU

Debugging toolkit ​

QuestionCommandWhat you learn
Does the Service have backends?kubectl get endpointslices -l kubernetes.io/service-name=X -o wideReady pod IPs, ports, conditions
Are ports and selector right?kubectl describe svc XPort, TargetPort, Endpoints, Events (LB errors)
Does it work from inside?kubectl run -it --rm tmp --image=nicolaka/netshoot -- bash, then curl, dig, nc -zvThe real in-cluster path, DNS and policy included
Is the app itself up?kubectl port-forward pod/X 8080:8080Bypasses Service and policy: isolates the app
What does the pod listen on?kubectl exec X -- ss -lntp (or netstat)127.0.0.1 vs 0.0.0.0 binding
What rules did kube-proxy write?iptables-save -t nat | grep SERVICE_NAME / nft list table ip kube-proxy on the nodeVIP, NodePort, endpoint DNAT
Which connections exist?conntrack -L -d CLUSTER_IP on the node; conntrack -S for dropsThe DNAT decision per flow, table pressure
What do packets look like?kubectl debug node/N -it --image=nicolaka/netshoot then tcpdump -ni any port 53Wire-level truth on the node
Cilium datapathcilium monitor (in the agent pod), hubble observe --namespace labDrops with reasons (policy denied, no endpoint)
DNS server sideadd log to the Corefile; kubectl -n kube-system logs -l k8s-app=kube-dnsWhich names pods actually ask
Gateway / Route statekubectl describe httproute XAccepted, ResolvedRefs conditions and reasons

Typical error messages ​

The strings below are the usual forms (exact wording varies by tool version); what matters is which layer each one points at.

MessageWhereMeaning
curl: (7) Failed to connect to whoami port 80 after 2 ms: Couldn't connect to serverClient podNo endpoints: kube-proxy installs a REJECT for Services without endpoints
curl: (28) Connection timed out / context deadline exceededClientPackets dropped: NetworkPolicy, security group, MTU, wrong node
** server can't find whoami.lab: NXDOMAINnslookupWrong namespace or name; Service missing
;; connection timed out; no servers could be reacheddigDNS egress blocked (NetworkPolicy) or CoreDNS down
EXTERNAL-IP <pending>kubectl get svcNo LoadBalancer controller handled it
Warning FailedCreatePodSandBox ... failed to setup network for sandboxPod eventsCNI ADD failed
nf_conntrack: table full, dropping packetNode dmesgconntrack exhausted
error: unable to forward port because pod is not runningkubectl port-forwardPod not Running
HTTPRoute ... Accepted=False reason=NotAllowedByListenersRoute statusGateway allowedRoutes excludes the namespace
502 Bad Gateway / 503 Service Unavailable from the proxyIngress / GatewayPod gone during rollout or no ready endpoints

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
502s on every deployReadiness + graceful drainFail readiness on SIGTERM, sleep, then shut down; preStopZero-downtime rolloutsSlower rollouts
One pod gets all gRPC loadHeadless + client-side LB, or a mesh / L7 Gatewaydns:/// resolver, round_robinPer-request balanceClient complexity
Need to hit every replicaHeadless Service fan-outResolve A records, call eachNo registry neededOnly ready pods; races with scaling
Slow outbound callsFix ndotsTrailing dot, ndots: "2", NodeLocal DNSCacheFewer DNS queriesConfig per pod
Real client IPexternalTrafficPolicy: Local or trusted X-Forwarded-ForService field / TrustProxiesCorrect rate limits, logsUneven load / proxy config
Lateral movementNetworkPolicy default denyPolicies per namespaceSmall blast radiusMust allow DNS and each flow
Partner IP allow-listStatic egress IPNAT gateway or egress gatewayStable IPCost, extra hop
Config breaks on rescheduleService DNS names everywhereConfigMap with FQDNsSurvives restartsOne search miss with ndots 5

A whoami service with correct probes and drain (Go) ​

The lab's service: prints pod IP, node, the TCP peer and forwarded headers; /healthz for liveness (process only), /readyz for readiness (false during warm-up and after SIGTERM), and a drain delay so kube-proxy and the gateway stop sending before it exits.

go
// Command whoami is the lab service: it prints which pod and node answered,
// the TCP peer the pod saw and the forwarded headers, and exposes
// liveness and readiness endpoints that behave correctly during a rollout.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net"
	"net/http"
	"os"
	"os/signal"
	"sort"
	"strings"
	"sync/atomic"
	"syscall"
	"time"
)

type reply struct {
	Hostname   string              `json:"hostname"`
	PodIP      string              `json:"pod_ip"`
	NodeName   string              `json:"node_name"`
	Namespace  string              `json:"namespace"`
	Version    string              `json:"version"`
	RemoteAddr string              `json:"remote_addr"`
	Host       string              `json:"host"`
	Forwarded  map[string][]string `json:"forwarded,omitempty"`
	Interfaces []string            `json:"interfaces"`
}

// localAddrs lists the non-loopback addresses inside the pod's network
// namespace; with one IP per pod this is usually exactly one address.
func localAddrs() []string {
	var out []string
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return out
	}
	for _, a := range addrs {
		if ipn, ok := a.(*net.IPNet); ok && !ipn.IP.IsLoopback() {
			out = append(out, ipn.String())
		}
	}
	sort.Strings(out)
	return out
}

func main() {
	addr := ":" + envOr("PORT", "8080")
	var ready atomic.Bool // false until warm-up is done, false again on SIGTERM

	mux := http.NewServeMux()
	mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
		host, _ := os.Hostname()
		fwd := map[string][]string{}
		for k, v := range r.Header {
			lk := strings.ToLower(k)
			if strings.HasPrefix(lk, "x-forwarded-") || lk == "x-real-ip" || lk == "forwarded" {
				fwd[k] = v
			}
		}
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(reply{
			Hostname:   host,
			PodIP:      os.Getenv("POD_IP"), // injected by the downward API
			NodeName:   os.Getenv("NODE_NAME"),
			Namespace:  os.Getenv("POD_NAMESPACE"),
			Version:    envOr("VERSION", "v1"),
			RemoteAddr: r.RemoteAddr, // the TCP peer: client, node (SNAT) or proxy
			Host:       r.Host,
			Forwarded:  fwd,
			Interfaces: localAddrs(),
		})
	})
	// Liveness: "is the process stuck?" Never check dependencies here,
	// or a database outage restarts every pod in the fleet.
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	// Readiness: "should the Service send me traffic?" A failing readiness
	// probe moves the pod's address to ready=false in its EndpointSlice.
	mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
		if !ready.Load() {
			http.Error(w, "not ready", http.StatusServiceUnavailable)
			return
		}
		w.WriteHeader(http.StatusOK)
	})

	srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
	go func() {
		time.Sleep(2 * time.Second) // stand-in for cache warm-up, migrations check, etc.
		ready.Store(true)
	}()

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
	defer stop()
	go func() {
		slog.Info("listening", "addr", addr)
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			slog.Error("serve", "err", err)
			os.Exit(1)
		}
	}()

	<-ctx.Done()
	// Graceful drain: report not-ready, keep serving while kube-proxy,
	// CoreDNS and the ingress controller notice the endpoint is gone,
	// then stop accepting and finish in-flight requests.
	ready.Store(false)
	time.Sleep(durationOr("DRAIN_DELAY", 5*time.Second))
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	_ = srv.Shutdown(shutdownCtx)
	slog.Info("stopped")
}

func envOr(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

func durationOr(k string, def time.Duration) time.Duration {
	if d, err := time.ParseDuration(os.Getenv(k)); err == nil {
		return d
	}
	return def
}
FROM golang:1.24-alpine AS build
WORKDIR /src
COPY go.mod ./
COPY whoami/ ./whoami/
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /whoami ./whoami

FROM scratch
COPY --from=build /whoami /whoami
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["/whoami"]

Talking to every pod behind a headless Service (Go) ​

Resolves the headless name (with a trailing dot, so ndots is skipped), prints SRV records for the named port and calls each pod in parallel.

go
// Command headless resolves a headless Service (clusterIP: None), which
// returns one A/AAAA record per ready pod instead of a single virtual IP,
// and then talks to every pod directly. This is how a client does its own
// load balancing, fan-out or shard routing inside Kubernetes.
package main

import (
	"context"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"sort"
	"sync"
	"time"
)

func main() {
	// Fully qualified with a trailing dot: one DNS query, no search-list walk.
	name := "whoami-headless.lab.svc.cluster.local."
	port := "8080"
	if len(os.Args) > 1 {
		name = os.Args[1]
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	var r net.Resolver
	ips, err := r.LookupHost(ctx, name)
	if err != nil {
		fmt.Fprintln(os.Stderr, "lookup:", err)
		os.Exit(1)
	}
	sort.Strings(ips)
	fmt.Printf("%s -> %d pod addresses %v\n", name, len(ips), ips)

	// Named ports publish SRV records: _http._tcp.<svc>.<ns>.svc.cluster.local
	if _, srvs, err := r.LookupSRV(ctx, "http", "tcp", name); err == nil {
		for _, s := range srvs {
			fmt.Printf("SRV %s:%d\n", s.Target, s.Port)
		}
	}

	client := &http.Client{Timeout: 2 * time.Second}
	var wg sync.WaitGroup
	results := make([]string, len(ips))
	for i, ip := range ips {
		wg.Add(1)
		go func(i int, ip string) {
			defer wg.Done()
			resp, err := client.Get("http://" + net.JoinHostPort(ip, port) + "/")
			if err != nil {
				results[i] = ip + " error: " + err.Error() + "\n"
				return
			}
			defer resp.Body.Close()
			b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
			results[i] = ip + " " + string(b)
		}(i, ip)
	}
	wg.Wait()
	for _, line := range results {
		fmt.Print(line)
	}
}

Printing the ndots query list (Go) ​

Feed it a pod's resolv.conf (kubectl exec POD -- cat /etc/resolv.conf > r.conf) and a name; it prints the questions the stub resolver will ask, in order. Real output on this machine:

text
$ go run ./ndots api.stripe.com resolv.conf
ndots=5 search=[lab.svc.cluster.local svc.cluster.local cluster.local]
1  A? api.stripe.com.lab.svc.cluster.local.   AAAA? api.stripe.com.lab.svc.cluster.local.
2  A? api.stripe.com.svc.cluster.local.   AAAA? api.stripe.com.svc.cluster.local.
3  A? api.stripe.com.cluster.local.   AAAA? api.stripe.com.cluster.local.
4  A? api.stripe.com.   AAAA? api.stripe.com.
$ go run ./ndots api.stripe.com. resolv.conf
ndots=5 search=[lab.svc.cluster.local svc.cluster.local cluster.local]
1  A? api.stripe.com.   AAAA? api.stripe.com.
go
// Command ndots shows which DNS questions a glibc/musl-style stub resolver
// asks for a name, given the search list and ndots from /etc/resolv.conf.
// Run it with a pod's resolv.conf to see why "api.stripe.com" costs up to
// eight queries (four suffixes times A and AAAA) before the real answer.
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type conf struct {
	search []string
	ndots  int
}

func parse(path string) (conf, error) {
	c := conf{ndots: 1} // resolv.conf default
	f, err := os.Open(path)
	if err != nil {
		return c, err
	}
	defer f.Close()
	sc := bufio.NewScanner(f)
	for sc.Scan() {
		fields := strings.Fields(sc.Text())
		if len(fields) == 0 {
			continue
		}
		switch fields[0] {
		case "search":
			c.search = fields[1:]
		case "options":
			for _, o := range fields[1:] {
				if v, ok := strings.CutPrefix(o, "ndots:"); ok {
					if n, err := strconv.Atoi(v); err == nil {
						c.ndots = n
					}
				}
			}
		}
	}
	return c, sc.Err()
}

// candidates returns the names tried in order. A trailing dot means
// "absolute": exactly one name, the search list is skipped.
func candidates(name string, c conf) []string {
	if strings.HasSuffix(name, ".") {
		return []string{name}
	}
	var out []string
	asIs := name + "."
	if strings.Count(name, ".") >= c.ndots {
		out = append(out, asIs)
	}
	for _, s := range c.search {
		out = append(out, name+"."+s+".")
	}
	if strings.Count(name, ".") < c.ndots {
		out = append(out, asIs)
	}
	return out
}

func main() {
	path := "/etc/resolv.conf"
	if len(os.Args) < 2 {
		fmt.Fprintln(os.Stderr, "usage: ndots NAME [resolv.conf]")
		os.Exit(2)
	}
	if len(os.Args) > 2 {
		path = os.Args[2]
	}
	c, err := parse(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Printf("ndots=%d search=%v\n", c.ndots, c.search)
	for i, q := range candidates(os.Args[1], c) {
		fmt.Printf("%d  A? %s   AAAA? %s\n", i+1, q, q)
	}
}

Laravel: trusting the ingress or gateway ​

Behind ingress-nginx or any Gateway implementation, the TCP peer of every request is the proxy pod. Trust exactly the CIDR those pods live in; Laravel's docs show trustProxies(at: '*') for cloud load balancers whose addresses you cannot know, which inside a cluster means any pod could spoof X-Forwarded-For if it can reach your pod directly (pair it with a NetworkPolicy that only admits the gateway).

php
<?php

// bootstrap/app.php (Laravel 13) for a pod behind ingress-nginx or a Gateway API
// implementation (Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric).
// The TCP peer of every request is the proxy pod, so trust ONLY the pod CIDR
// the proxies live in (kind: 10.244.0.0/16; read yours from
// `kubectl get nodes -o jsonpath='{.items[*].spec.podCIDR}'`).
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        // Built-in liveness endpoint: returns 200 when the app boots.
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->trustProxies(
            at: explode(',', env('TRUSTED_PROXY_CIDRS', '10.244.0.0/16')),
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO,
        );
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })
    ->create();

Laravel: probes, Service DNS names and the whoami endpoint ​

Liveness on Laravel's built-in /up route; readiness checks the two dependencies this pod cannot serve without; config points at Service DNS names.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Throwable;

// Readiness for the kubelet: "can THIS pod serve a request right now?"
// Liveness stays on Laravel's built-in /up route, which (without DiagnosingHealth
// listeners) never touches dependencies: a database outage must not restart every pod.
class HealthController extends Controller
{
    public function ready(): JsonResponse
    {
        // Two cheap round trips with short timeouts. Keep the probe period at
        // 5 s or more: every pod probes every dependency, so 300 pods probing
        // every second is 600 extra queries per second on Postgres and Redis.
        $checks = [
            'database' => $this->check(fn () => DB::select('SELECT 1')),
            'redis' => $this->check(fn () => Redis::connection()->ping()),
        ];

        $ok = ! in_array(false, $checks, true);

        return response()->json(['ready' => $ok, 'checks' => $checks], $ok ? 200 : 503);
    }

    public function whoami(): JsonResponse
    {
        return response()->json([
            'pod' => gethostname(),
            // Real process env vars from the downward API; read with getenv() because
            // env() outside config files breaks for .env values after config:cache.
            'pod_ip' => getenv('POD_IP') ?: null,
            'node' => getenv('NODE_NAME') ?: null,
            // TCP peer: the ingress / gateway pod, or a node IP after SNAT.
            'remote_addr' => request()->server('REMOTE_ADDR'),
            // Real client after TrustProxies walked X-Forwarded-For.
            'client_ip' => request()->ip(),
            'scheme' => request()->getScheme(),
            'host' => request()->getHost(),
        ]);
    }

    private function check(callable $probe): bool
    {
        try {
            $probe();

            return true;
        } catch (Throwable) {
            return false;
        }
    }
}
php
<?php

// routes/web.php: probe and debug endpoints, outside session/CSRF middleware.
use App\Http\Controllers\HealthController;
use Illuminate\Support\Facades\Route;

Route::get('/readyz', [HealthController::class, 'ready'])
    ->withoutMiddleware('web');
Route::get('/whoami', [HealthController::class, 'whoami']);
php
<?php

// The .env values a Laravel pod needs inside Kubernetes, delivered by a
// ConfigMap/Secret (see k8s/laravel.yaml). Every host is a Service DNS name,
// never a pod IP: pod IPs change on every restart, the Service name does not.
//
//   DB_HOST=postgres-rw.db.svc.cluster.local      # 4 dots < ndots:5: tries the search list first
//   REDIS_HOST=redis.cache.svc.cluster.local
//   MAIL_HOST=mailpit.tools.svc.cluster.local
//   PAYMENTS_URL=http://payments.payments.svc.cluster.local
//
// config/database.php reads them unchanged:
return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'app'),
            'username' => env('DB_USERNAME', 'app'),
            'password' => env('DB_PASSWORD', ''),
            // A long-lived Octane/Horizon worker keeps its connection; if the
            // Service's backend moves, the next query reconnects on error.
        ],
    ],
    'redis' => [
        'client' => env('REDIS_CLIENT', 'phpredis'),
        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'port' => env('REDIS_PORT', '6379'),
            'password' => env('REDIS_PASSWORD'),
            'database' => env('REDIS_DB', '0'),
            // Fail fast inside the cluster instead of hanging a worker.
            'timeout' => 2.0,
            'read_timeout' => 5.0,
        ],
    ],
];

Laravel: calling every replica ​

The PHP twin of the Go headless client, using dns_get_record() and Http::pool() with named requests.

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;

// php artisan cluster:fan-out whoami-headless.lab.svc.cluster.local
// Resolves a headless Service (one A record per ready pod) and calls every
// pod directly, e.g. to clear a per-pod in-memory cache in all replicas.
class FanOutToPods extends Command
{
    protected $signature = 'cluster:fan-out {service} {--port=8080} {--path=/}';

    protected $description = 'Call every pod behind a headless Service';

    public function handle(): int
    {
        // Trailing dot: absolute name, no ndots search-list expansion.
        $records = dns_get_record(rtrim($this->argument('service'), '.').'.', DNS_A) ?: [];
        $ips = array_column($records, 'ip');

        if ($ips === []) {
            $this->error('No A records: is the Service headless and are pods Ready?');

            return self::FAILURE;
        }

        $port = (int) $this->option('port');
        $path = $this->option('path');

        $responses = Http::pool(fn (Pool $pool) => array_map(
            fn (string $ip) => $pool->as($ip)->timeout(2)->get("http://{$ip}:{$port}{$path}"),
            $ips,
        ));

        foreach ($responses as $ip => $response) {
            $this->line($ip.' -> '.($response instanceof \Throwable ? $response->getMessage() : $response->status()));
        }

        return self::SUCCESS;
    }
}

Laravel on Kubernetes: Octane behind an HTTPRoute, Horizon as a Deployment ​

Web pods run Octane (FrankenPHP) behind a Gateway API HTTPRoute; Horizon workers are a separate Deployment with no Service (they only connect out); both reach Redis and Postgres by Service DNS name; Redis admits only the app's pods.

yaml
# Laravel on Kubernetes: Octane web pods behind a Gateway API HTTPRoute,
# Horizon workers as a separate Deployment, both reaching Redis and
# Postgres through Service DNS names from one ConfigMap.
apiVersion: v1
kind: ConfigMap
metadata:
  name: shop-env
  namespace: shop
data:
  APP_ENV: production
  DB_HOST: postgres-rw.db.svc.cluster.local
  REDIS_HOST: redis.cache.svc.cluster.local
  QUEUE_CONNECTION: redis
  TRUSTED_PROXY_CIDRS: 10.244.0.0/16
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-web
  namespace: shop
spec:
  replicas: 3
  selector:
    matchLabels: { app: shop, role: web }
  template:
    metadata:
      labels: { app: shop, role: web }
    spec:
      containers:
        - name: octane
          image: registry.example.com/shop:1.42.0
          args: ["php", "artisan", "octane:start", "--server=frankenphp", "--host=0.0.0.0", "--port=8000"]
          ports:
            - { name: http, containerPort: 8000 }
          envFrom:
            - configMapRef: { name: shop-env }
            - secretRef: { name: shop-secrets }
          env:
            - name: POD_IP
              valueFrom: { fieldRef: { fieldPath: status.podIP } }
            - name: NODE_NAME
              valueFrom: { fieldRef: { fieldPath: spec.nodeName } }
          readinessProbe:
            httpGet: { path: /readyz, port: http }
            periodSeconds: 5
          livenessProbe:
            httpGet: { path: /up, port: http }
            periodSeconds: 10
          lifecycle:
            # Give kube-proxy and the gateway time to drop this endpoint
            # before Octane stops accepting connections.
            preStop:
              exec: { command: ["sleep", "5"] }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-horizon
  namespace: shop
spec:
  replicas: 2
  selector:
    matchLabels: { app: shop, role: horizon }
  template:
    metadata:
      labels: { app: shop, role: horizon }
    spec:
      terminationGracePeriodSeconds: 120   # let running jobs finish
      containers:
        - name: horizon
          image: registry.example.com/shop:1.42.0
          args: ["php", "artisan", "horizon"]
          envFrom:
            - configMapRef: { name: shop-env }
            - secretRef: { name: shop-secrets }
          # No Service and no ports: workers only make outbound connections.
---
apiVersion: v1
kind: Service
metadata:
  name: shop-web
  namespace: shop
spec:
  selector: { app: shop, role: web }
  ports:
    - { name: http, port: 80, targetPort: http }
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
  namespace: shop
spec:
  parentRefs:
    - name: public
      namespace: gateway-infra
  hostnames: ["shop.example.com"]
  rules:
    - matches:
        - path: { type: PathPrefix, value: / }
      backendRefs:
        - { name: shop-web, port: 80 }
---
# Horizon and web pods may reach Redis; nothing else in the namespace may.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: redis-from-shop
  namespace: cache
spec:
  podSelector:
    matchLabels: { app: redis }
  policyTypes: [Ingress]
  ingress:
    - from:
        - namespaceSelector:
            matchLabels: { kubernetes.io/metadata.name: shop }
          podSelector:
            matchLabels: { app: shop }
      ports:
        - { protocol: TCP, port: 6379 }

Detecting lost client IPs in your data (SQL) ​

If your access log stores the client IP, a query tells you whether SNAT is eating it: when most "clients" are inside the pod or node ranges, externalTrafficPolicy or TrustProxies is wrong. PostgreSQL's inet type and the << (is contained by) operator do the work.

sql
-- PostgreSQL: request_log(client_ip inet, peer_ip inet, created_at timestamptz)
SELECT
  CASE
    WHEN client_ip << inet '10.244.0.0/16' THEN 'pod CIDR (SNAT by node or proxy not trusted)'
    WHEN client_ip << inet '172.18.0.0/16' THEN 'node network (NodePort SNAT)'
    ELSE 'real client'
  END AS source_kind,
  count(*) AS requests,
  count(DISTINCT client_ip) AS distinct_ips
FROM request_log
WHERE created_at > now() - interval '1 hour'
GROUP BY 1
ORDER BY requests DESC;

Common failures ​

SymptomLikely causeCheckFix
Service has no endpoints; curl refused instantlySelector does not match pod labels, or pods not Readykubectl get endpointslices -l kubernetes.io/service-name=X; kubectl get pods --show-labelsFix labels/selector; fix the readiness probe
Works with port-forward, fails via ServiceWrong targetPort, app listens on 127.0.0.1, NetworkPolicykubectl describe svc X; ss -lntp in the podListen on 0.0.0.0; name ports; allow the flow
ClusterIP unreachable from your laptopExpected: ClusterIPs exist only as rules on cluster nodescurl from a podNodePort, LoadBalancer or port-forward from outside
ClusterIP reachable from pods but not from a cluster nodeA fault: node-local traffic also goes through OUTPUT → KUBE-SERVICES; suspect the node's route to remote pod CIDRs, the overlay source address, or a host firewallcurl from the node; ip route; iptables-save -t nat | grep KUBE-SERVICESFix CNI routes / MTU / host firewall
NodePort works from inside, times out from outsideCloud security group / firewall blocks 30000-32767; nftables --nodeport-addresses primaryTry from another nodeOpen the range from the LB; set --nodeport-addresses
EXTERNAL-IP <pending> foreverNo LB controller (kind, bare metal), wrong loadBalancerClasskubectl describe svc; controller logsInstall cloud-provider-kind / MetalLB / AWS LBC
Outbound calls slow, DNS heavyndots:5 search walk, UDP conntrack racestcpdump port 53 in the podFQDN with trailing dot, ndots: "2", NodeLocal DNSCache
App logs show node or pod IPs as clientsSNAT (externalTrafficPolicy: Cluster) or untrusted proxy headersLog RemoteAddr and X-Forwarded-ForLocal policy on the gateway Service; TrustProxies with the gateway CIDR
Everything broke after default-denyDNS egress not allowed; only one side of a flow alloweddig from the pod times outAdd the allow-DNS policy; allow egress and ingress
Small requests work, large ones hangMTU mismatch on overlay or VPNping -M do -s 1422; compare ip link MTUsSet CNI MTU = underlay − overhead
502/503 during deploysPod exits before endpoints are removedProxy logs during rolloutReadiness off on SIGTERM + drain delay / preStop
One pod overloaded, others idleLong-lived connections (HTTP/2, gRPC, keep-alive)Per-pod request rateHeadless + client LB, L7 gateway or mesh, MaxConnectionAge
Intermittent Connection reset by peer on long connectionsconntrack issue on kernels before 6.1, idle timeouts on LBs/NATkube-proxy metric iptables_ct_state_invalid_dropped_packets_totalUpgrade kernel; --conntrack-tcp-be-liberal; TCP keepalives
Policy "has no effect"CNI does not enforce NetworkPolicyTest a denyUse Calico/Cilium/Antrea or a CNI with policy

Choosing ​

SituationChooseExtra techniqueReason
In-cluster HTTP/JSON between servicesClusterIP Service + DNS nameReadiness probes, drain on SIGTERMSimple; per-connection balance is fine for short connections
In-cluster gRPC / HTTP/2Headless + client-side round_robin, or a meshMaxConnectionAge on the serverOne connection would pin one pod
Stateful peers (Kafka, etcd, Postgres replicas)StatefulSet + headless ServicepublishNotReadyAddresses for bootstrapStable per-pod names
Public HTTP(S), new clusterGateway API (Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, cloud)One Gateway per trust zone, HTTPRoute per appRole split, typed canaries, active API
Public HTTP(S), existing IngressesKeep Ingress, plan migration off ingress-nginxGateway API migration guidesIngress frozen; Ingress NGINX retired March 2026
Raw TCP/UDP from outsidetype: LoadBalancer (cloud, MetalLB)externalTrafficPolicy: Local or PROXY protocolL4 path, keep client IP
Bare metal / on-premMetalLB (L2 or BGP) or Cilium LB IPAMCalico/Cilium BGP for pod routesNo cloud controller
Local devkind + extraPortMappings or cloud-provider-kindport-forward for one-offsReal data path on a laptop
Large cluster (10k+ Services)kube-proxy nftables or Cilium kube-proxy replacementSet the mode explicitlyO(1) lookups, fast updates
IPVS todayMigrate to nftablesTest NodePort and firewall differencesDeprecated v1.35, removed v1.43
Multi-tenant clusterNetworkPolicy default deny per namespaceAdminNetworkPolicy, Cilium/Calico tiersBlast radius
Partner IP allow-listsNAT gateway static IP or egress gatewayDedicated egress nodesPod IPs are not stable or public
Cross-zone cost/latencytrafficDistribution: PreferSameZone≥ 3 endpoints per zoneKeeps traffic local without hard failure
DNS-heavy egressNodeLocal DNSCache + FQDNsndots: "2" on hot podsFewer queries, no conntrack races

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

A single Laravel app moved into Kubernetes is three Deployments and three Services: shop-web (Octane), shop-horizon (no Service), and Postgres/Redis (often managed outside the cluster). The networking that matters is small: Service DNS names in .env (config), one Gateway or Ingress for the web pods, TrustProxies set to the gateway's pod CIDR, readiness on /readyz, liveness on /up, and a preStop sleep. Everyday example: a shop whose checkout returned 502 for 2 seconds on every deploy; the fix was not more replicas but the drain sequence in the Go whoami and the Laravel manifest.

Modular monolith (one deployable, several modules and stores) ​

Modules still share a process, but their stores become separate Services: billing-db.billing.svc.cluster.local, search.search.svc.cluster.local. Namespaces become the module boundary and NetworkPolicy the enforcement: only pods labelled module=billing may reach billing-db. Production example: a modular Laravel monolith where the reporting module's heavy queries go to a read replica Service (postgres-ro), and a NetworkPolicy keeps the public web pods from ever reaching the payments database even though they run the same image with a different label.

Microservices ​

Every service is a Deployment + ClusterIP Service; discovery is DNS (server-side discovery through the VIP, or client-side through headless Services, see service discovery). What crosses boundaries: names (stable), not IPs (ephemeral); connection-level balancing (so gRPC needs headless or a mesh); per-hop SNAT rules (so the client IP must travel in X-Forwarded-For or a trace header); NetworkPolicy per flow. A typical flow: Gateway → orders (Go) → payments (Laravel) → Redis, where the Gateway HTTPRoute does the 90/10 canary for orders, orders reaches payments.payments.svc.cluster.local through kube-proxy, and payments sees orders' real pod IP (pod-to-pod has no NAT), which a mesh would turn into an mTLS identity. Where an API gateway, BFF or mesh fits on top is the subject of API gateway, BFF and service mesh.

Distributed data: replicas, caches and multi-cluster ​

Databases in the cluster are StatefulSets behind two Services: a ClusterIP postgres-rw that follows the primary (the operator moves the selector or the EndpointSlice on failover) and postgres-ro across replicas. Clients holding pooled connections to the old primary keep them until they break, so failover time is bounded by TCP timeouts and pool settings, not by DNS. Redis Cluster and Kafka clients need every member's address: headless Services plus per-pod names, and for clients outside the cluster, one LoadBalancer or NodePort per broker (Kafka's advertised.listeners). Multi-cluster adds clusterset.local names (MCS API), Cilium Cluster Mesh or a mesh's east-west gateways; latency and egress cost then dominate, which is where trafficDistribution and zone-local replicas pay off. Production example: a three-zone cluster where a Redis cache per zone plus PreferSameZone cut cross-AZ data transfer while keeping fallback when a zone's cache pods restart.

Scaling path ​

LoadWhat changes in the networkExample
1× (one team, tens of Services)Defaults: iptables kube-proxy, CoreDNS ×2, one Gatewaykind locally, a small EKS cluster
10× (hundreds of Services, thousands of pods)nftables or eBPF kube-proxy replacement; NodeLocal DNSCache; HPA on CoreDNS; NetworkPolicy everywhere; IP planning for pod CIDRs (VPC-native IP exhaustion)Multi-team platform with a shared Gateway
100× (tens of thousands of Services, many clusters)eBPF datapath (Cilium) with Maglev/DSR; per-zone routing; dedicated egress gateways; multi-cluster service discovery; EndpointSlice and API-server watch load become the limitsFleet of clusters per region with a global LB in front

Lab ​

Written for kind v0.33.0 (node image kindest/node:v1.37.0), kubectl and Docker Desktop. For this revision the cluster could not be created on the author's machine (the 1.37 node image did not finish downloading over the available link), so every cluster output is marked # expected and is constructed from the documented behaviour quoted above, not captured; the DNS capture, the hex dump and the Go program outputs were captured for real. All files are in docs/snippets/foundations/kubernetes-networking/ (k8s/ manifests, go/ programs).

1. Create a three-node cluster. extraPortMappings exposes NodePort 30080 of the control-plane container on localhost:30080.

bash
go install sigs.k8s.io/kind@v0.33.0
cat > kind.yaml <<'YAML'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: knet
networking:
  kubeProxyMode: iptables        # try nftables later
nodes:
- role: control-plane
  extraPortMappings:
  - containerPort: 30080
    hostPort: 30080
- role: worker
- role: worker
YAML
kind create cluster --config kind.yaml
kubectl get nodes -o custom-columns=NAME:.metadata.name,IP:.status.addresses[0].address,PODCIDR:.spec.podCIDR
# expected
# NAME                 IP           PODCIDR
# knet-control-plane   172.18.0.2   10.244.0.0/24
# knet-worker          172.18.0.4   10.244.1.0/24
# knet-worker2         172.18.0.3   10.244.2.0/24

2. Deploy whoami ×3 and three Services. The manifests (Deployment with downward-API env and probes, ClusterIP, NodePort, headless) and the debug pod:

yaml
# Namespace, a 3-replica whoami Deployment and three Services that select
# the same pods: ClusterIP (virtual IP), NodePort (every node's port 30080)
# and headless (DNS returns the pod IPs, no virtual IP, no kube-proxy).
apiVersion: v1
kind: Namespace
metadata:
  name: lab
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: whoami
  namespace: lab
spec:
  replicas: 3
  selector:
    matchLabels: { app: whoami, track: stable }
  template:
    metadata:
      labels: { app: whoami, track: stable }
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: whoami
          image: academy/whoami:v1
          imagePullPolicy: IfNotPresent
          ports:
            - { name: http, containerPort: 8080 }
          env:
            - name: POD_IP
              valueFrom: { fieldRef: { fieldPath: status.podIP } }
            - name: NODE_NAME
              valueFrom: { fieldRef: { fieldPath: spec.nodeName } }
            - name: POD_NAMESPACE
              valueFrom: { fieldRef: { fieldPath: metadata.namespace } }
            - { name: VERSION, value: v1 }
          readinessProbe:
            httpGet: { path: /readyz, port: http }
            periodSeconds: 2
            failureThreshold: 1
          livenessProbe:
            httpGet: { path: /healthz, port: http }
            periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
  name: whoami
  namespace: lab
spec:
  type: ClusterIP
  selector: { app: whoami }
  ports:
    - { name: http, port: 80, targetPort: http }
---
apiVersion: v1
kind: Service
metadata:
  name: whoami-nodeport
  namespace: lab
spec:
  type: NodePort
  selector: { app: whoami }
  ports:
    - { name: http, port: 80, targetPort: http, nodePort: 30080 }
---
apiVersion: v1
kind: Service
metadata:
  name: whoami-headless
  namespace: lab
spec:
  clusterIP: None
  selector: { app: whoami }
  ports:
    - { name: http, port: 8080, targetPort: http }
yaml
# A debugging pod with dig, nslookup, curl, tcpdump, conntrack, iptables.
apiVersion: v1
kind: Pod
metadata:
  name: netshoot
  namespace: lab
  labels: { app: netshoot }
spec:
  containers:
    - name: netshoot
      image: nicolaka/netshoot:latest
      command: ["sleep", "infinity"]
bash
cd docs/snippets/foundations/kubernetes-networking
docker build -t academy/whoami:v1 -f go/whoami/Dockerfile go
kind load docker-image academy/whoami:v1 --name knet
kubectl apply -f k8s/whoami.yaml -f k8s/netshoot.yaml
kubectl -n lab get pods -o wide
kubectl -n lab get svc
kubectl -n lab get endpointslices -l kubernetes.io/service-name=whoami
# expected
# NAME              TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
# whoami            ClusterIP   10.96.84.19    <none>        80/TCP         10s
# whoami-headless   ClusterIP   None           <none>        8080/TCP       10s
# whoami-nodeport   NodePort    10.96.201.7    <none>        80:30080/TCP   10s
# NAME           ADDRESSTYPE   PORTS   ENDPOINTS                          AGE
# whoami-x7k2p   IPv4          8080    10.244.1.5,10.244.2.7,10.244.2.8   10s

3. ClusterIP balances connections; headless returns pods.

bash
kubectl -n lab exec netshoot -- sh -c 'for i in $(seq 1 9); do curl -s whoami/ | jq -r .hostname; done | sort | uniq -c'
# expected: roughly 3 / 3 / 3 across the three pod names (random per connection)
kubectl -n lab exec netshoot -- dig +short whoami-headless.lab.svc.cluster.local
kubectl -n lab exec netshoot -- dig +short SRV _http._tcp.whoami-headless.lab.svc.cluster.local
# expected: three pod IPs; SRV lines "0 33 8080 10-244-1-5.whoami-headless.lab.svc.cluster.local."
GOOS=linux GOARCH=arm64 go build -C go -o /tmp/headless ./headless   # GOARCH=amd64 on Intel
kubectl -n lab cp /tmp/headless netshoot:/tmp/headless
kubectl -n lab exec netshoot -- /tmp/headless
# expected: "whoami-headless.lab.svc.cluster.local. -> 3 pod addresses [...]" and one JSON line per pod

4. Look at the rules on a node. kind nodes are containers, so docker exec is a shell on the node.

bash
docker exec knet-worker iptables-save -t nat | grep -E 'lab/whoami' | head -20
docker exec knet-worker sh -c 'iptables-save -t nat | grep -c KUBE-SEP'
docker exec knet-worker conntrack -L -d 10.96.84.19 2>/dev/null | head
# expected conntrack line:
# tcp 6 117 TIME_WAIT src=10.244.1.6 dst=10.96.84.19 sport=41234 dport=80 src=10.244.2.7 dst=10.244.1.6 sport=8080 dport=41234 [ASSURED] mark=0 use=1

5. DNS and the ndots trace. The capture below was taken in a plain Docker container with the same resolv.conf a pod in namespace lab gets (--dns-search lab.svc.cluster.local --dns-search svc.cluster.local --dns-search cluster.local --dns-option ndots:5), and is real; in the cluster run the same commands in netshoot.

bash
kubectl -n lab exec netshoot -- cat /etc/resolv.conf
kubectl -n lab exec netshoot -- sh -c 'tcpdump -ni eth0 -l udp port 53 & sleep 1; getent hosts api.stripe.com; sleep 2; kill %1'
text
nameserver 1.1.1.1
search lab.svc.cluster.local svc.cluster.local cluster.local
options ndots:5
---
17:58:00.626006 IP 172.17.0.11.51848 > 1.1.1.1.53: 45853+ AAAA? api.stripe.com.svc.cluster.local. (50)
17:58:04.853883 IP 1.1.1.1.53 > 172.17.0.11.51848: 45853 NXDomain 0/1/0 (125)
17:58:04.853995 IP 172.17.0.11.56966 > 1.1.1.1.53: 37825+ AAAA? api.stripe.com.cluster.local. (46)
17:58:08.616602 IP 1.1.1.1.53 > 172.17.0.11.56966: 37825 NXDomain 0/1/0 (121)
17:58:08.616736 IP 172.17.0.11.45971 > 1.1.1.1.53: 12902+ AAAA? api.stripe.com. (32)
17:58:11.674566 IP 1.1.1.1.53 > 172.17.0.11.45971: 12902 0/1/0 (116)
17:58:11.674725 IP 172.17.0.11.51700 > 1.1.1.1.53: 136+ A? api.stripe.com.lab.svc.cluster.local. (54)
17:58:14.450413 IP 1.1.1.1.53 > 172.17.0.11.51700: 136 NXDomain 0/1/0 (129)
...
17:58:22.367687 IP 1.1.1.1.53 > 172.17.0.11.55308: 37983 3/0/0 A 34.241.202.139, A 34.240.123.193, A 34.241.54.72 (80)

On this (slow) link each NXDOMAIN took 1 to 4 seconds including a retry, so one lookup of api.stripe.com took over 20 seconds; with api.stripe.com. it was two questions. In a cluster CoreDNS answers the cluster.local misses itself in microseconds, but the extra round trips, conntrack entries and CoreDNS load remain.

6. NodePort and SNAT.

bash
curl -s localhost:30080/ | jq '{hostname, node_name, remote_addr}'
# expected: remote_addr is a node-side address (e.g. 10.244.0.1 or 172.18.0.2), not your laptop

7. Gateway API with a 90/10 canary (Envoy Gateway).

bash
# the chart installs the Gateway API CRDs too (per the Envoy Gateway quickstart)
helm install eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 -n envoy-gateway-system --create-namespace
kubectl apply -f k8s/whoami-v2.yaml -f k8s/gateway.yaml
kubectl -n lab get gateway,httproute
ENVOY_SVC=$(kubectl -n envoy-gateway-system get svc -o name \
  --selector=gateway.envoyproxy.io/owning-gateway-namespace=lab,gateway.envoyproxy.io/owning-gateway-name=web)
kubectl -n envoy-gateway-system port-forward $ENVOY_SVC 8888:80 &
for i in $(seq 1 200); do curl -s -H 'Host: whoami.example.test' localhost:8888/ | jq -r .version; done | sort | uniq -c
# expected: about 180 v1 and 20 v2

8. externalTrafficPolicy: Local and the client IP. Run the client as a container on kind's Docker network so no Docker Desktop NAT sits in between.

yaml
# externalTrafficPolicy: Local keeps the client source IP (no SNAT) but
# only nodes that run a ready pod answer; the others drop the traffic
# (cloud load balancers find out through healthCheckNodePort).
apiVersion: v1
kind: Service
metadata:
  name: whoami-local
  namespace: lab
spec:
  type: NodePort
  externalTrafficPolicy: Local
  selector: { app: whoami }
  ports:
    - { name: http, port: 80, targetPort: http, nodePort: 30081 }
bash
kubectl apply -f k8s/etp-local.yaml
kubectl -n lab get pods -o wide        # note which nodes run whoami pods
docker run --rm --network kind nicolaka/netshoot sh -c '
  ip -4 -o addr show eth0 | awk "{print \$4}"
  curl -s knet-worker:30080/ | jq -r .remote_addr     # Cluster policy
  curl -s knet-worker:30081/ | jq -r .remote_addr     # Local policy, node with a pod
  curl -s -m 3 knet-control-plane:30081/ || echo "no local endpoint: dropped"'
# expected:
# 172.18.0.5/16
# 10.244.1.1:51234        (SNAT: node-side address)
# 172.18.0.5:40112        (real client address preserved)
# no local endpoint: dropped

9. NetworkPolicy: default deny, allow DNS, allow one flow. Recent kind releases ship kindnet with NetworkPolicy support; the first blocked curl below proves whether your CNI enforces it. If it does not, recreate the cluster with disableDefaultCNI: true and install Calico, which the kind configuration docs list as known to work.

bash
kubectl -n lab exec netshoot -- curl -s -m 3 -o /dev/null -w '%{http_code}\n' https://example.com   # 200 before
kubectl apply -f k8s/netpol.yaml
kubectl -n lab exec netshoot -- curl -s -m 3 whoami/ | jq -r .hostname                            # allowed
kubectl -n lab exec netshoot -- curl -s -m 3 https://example.com || echo "egress blocked"          # blocked
kubectl -n lab delete networkpolicy allow-dns
kubectl -n lab exec netshoot -- nslookup whoami || echo "DNS blocked too"
kubectl apply -f k8s/netpol.yaml
# expected: a hostname, "egress blocked", then ";; connection timed out; no servers could be reached" and "DNS blocked too"

10. Clean up.

bash
kind delete cluster --name knet

Common misconceptions ​

BeliefReality
"The ClusterIP is a load balancer box"It is a DNAT rule on every node; no interface owns it
"Services balance requests"They balance connections; keep-alive pins a client to a pod
"ping the ClusterIP to test it"Rules match TCP/UDP ports only; test with curl/nc
"Pods see the real client IP"Not through NodePort/LoadBalancer by default (SNAT)
"externalTrafficPolicy: Local has no downside"Uneven load and drops on nodes without pods
"A NetworkPolicy always restricts traffic"Only if the CNI enforces it; flannel alone ignores it
"Default-deny egress is harmless"It blocks DNS unless you allow port 53
"port-forward works, so the Service works"It bypasses the Service, kube-proxy and policy
"Ingress exposes my app"Only with a controller; the controller's Service is what is exposed
"IPVS is the fast, modern mode"Deprecated since v1.35; nftables replaces it
"Pod IPs are stable enough to configure"They change on every reschedule; use Service names
"ExternalName proxies traffic"It is a CNAME only
"Overlay networks are just slower"The common failure is MTU, not throughput
"Each container in a pod has its own IP"They share one network namespace

Cheat sheet ​

TopicWhat to remember
Network modelOne IP per pod; pod to pod without NAT; node agents reach local pods
PodOne netns held by pause; veth to the node; CNI ADD/DEL
RangesPod CIDR (10.244.0.0/16 kind), Service CIDR (10.96.0.0/16 kind), node IPs; must not overlap anything you route to
Serviceport (VIP) vs targetPort (pod) vs nodePort (node); name your ports
EndpointSliceReady pod IPs; empty = selector/labels/readiness
kube-proxyiptables default; nftables stable and the future default; IPVS deprecated; Cilium replaces it with eBPF
ChainsKUBE-SERVICES → KUBE-SVC-* (random) → KUBE-SEP-* (DNAT); KUBE-MARK-MASQ 0x4000
NodePort30000-32767 on every node; SNAT under Cluster policy
LoadBalancerNeeds a controller; <pending> = none; MetalLB / cloud-provider-kind locally
Client IPexternalTrafficPolicy: Local or trusted X-Forwarded-For
DNSSVC.NS.svc.cluster.local; ndots:5; trailing dot; NodeLocal DNSCache; ClusterFirstWithHostNet
IngressFrozen API; needs a controller; annotations are not portable; Ingress NGINX retired March 2026
Gateway APIGatewayClass / Gateway / HTTPRoute / GRPCRoute; weights; role split
NetworkPolicyAllow-lists; default deny per namespace; allow DNS; both sides; CNI must enforce
EgressNode masquerade; NAT gateway / egress gateway for stable IPs; watch conntrack
Debugkubectl get endpointslices, kubectl describe svc, netshoot + dig/curl/tcpdump, iptables-save, conntrack -L, cilium monitor

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Service has port: 80 and targetPort: 8080, but curl whoami from a pod is refused immediately. What do you check first, and why "refused" rather than a timeout? Must-know ​

Answer

Answer: The EndpointSlice: kubectl get endpointslices -l kubernetes.io/service-name=whoami. An immediate refusal means kube-proxy installed its REJECT rule for a Service without ready endpoints, so the selector does not match the pod labels or the readiness probe fails. A timeout would point at drops (NetworkPolicy, MTU, firewall).

2 — Why can a pod reach 10.96.84.19:80 although no interface on any machine has that address? Must-know ​

Answer

Answer: kube-proxy on the client's node installed a rule matching destination 10.96.84.19:80 that DNATs the packet to a pod IP before routing. conntrack remembers the choice and rewrites the replies so the client only ever sees the VIP.

3 — In iptables mode, how are three endpoints given equal shares, and when is the choice made? Important ​

Answer

Answer: KUBE-SVC-* jumps to the first KUBE-SEP with probability 1/3, the second with 1/2 of the rest, and the third unconditionally. The choice is made on the first packet of a connection; later packets follow conntrack.

4 — Your gRPC client always talks to the same pod after a scale-up. Why, and what are two fixes? Important ​

Answer

Answer: gRPC keeps one long-lived HTTP/2 connection and kube-proxy balances connections. Use a headless Service with gRPC's DNS resolver and round_robin, or an L7 proxy/mesh that balances per request (and optionally MaxConnectionAge on the server).

5 — What does ndots:5 do to a lookup of api.stripe.com from namespace lab, and how do you avoid it? Important ​

Answer

Answer: The name has fewer than 5 dots, so the resolver tries api.stripe.com.lab.svc.cluster.local, .svc.cluster.local, .cluster.local first, for A and AAAA, before the real name. Use a trailing dot, lower ndots in dnsConfig, or NodeLocal DNSCache to make the misses cheap.

6 — Logs show every client as 10.244.0.1. Name two causes and their fixes. Important ​

Answer

Answer: NodePort/LoadBalancer SNAT under externalTrafficPolicy: Cluster (set Local on the gateway's Service), or the app does not trust the ingress/gateway and ignores X-Forwarded-For (configure trustProxies with the proxy pods' CIDR and restrict who can reach the app).

7 — A Service of type LoadBalancer on kind shows <pending>. Is the network broken? Important ​

Answer

Answer: No. Nothing implements LoadBalancer on kind by default. Run Cloud Provider KIND (or MetalLB); in clouds check the cloud controller or AWS Load Balancer Controller logs and the Service events.

8 — You applied a default-deny NetworkPolicy and now nothing resolves names, but liveness probes still pass. Explain both. Must-know ​

Answer

Answer: Default-deny egress blocks DNS to CoreDNS; add an egress rule to kube-system pods labelled k8s-app: kube-dns on UDP and TCP 53. Probes still pass because traffic from the pod's own node is always allowed.

9 — What does externalTrafficPolicy: Local change on a node that runs no pod of the Service, and how does a cloud LB cope? Important ​

Answer

Answer: That node drops the traffic (no forwarding to other nodes). Kubernetes allocates healthCheckNodePort; the LB health-checks it and stops sending to nodes without local ready endpoints.

10 — Why does kubectl port-forward svc/whoami 8080:80 succeed while in-cluster calls to whoami time out? Good to know ​

Answer

Answer: port-forward tunnels through the API server and kubelet straight into one pod; it bypasses kube-proxy, the ClusterIP and NetworkPolicy. A timeout in-cluster points to NetworkPolicy, a wrong targetPort/protocol, or a node/CNI problem.

11 — Small responses work, large ones hang between nodes on a VXLAN cluster. What is happening? Good to know ​

Answer

Answer: MTU: the pod MTU was not reduced by the 50-byte VXLAN overhead, so full-size packets exceed the underlay MTU and are dropped. Set the CNI MTU (for example 1450 on a 1500 network) or enable jumbo frames.

12 — Name the four stable Gateway API kinds and who owns each in a typical company. Good to know ​

Answer

Answer: GatewayClass (infrastructure provider / platform: which implementation), Gateway (cluster operator: listeners, TLS, allowed namespaces), HTTPRoute and GRPCRoute (application developers: matches and backends).

Glossary ​

TermMeaning
Pod network / cluster networkThe flat network giving each pod a routable IP
Network namespace (netns)Linux isolation of interfaces, routes and ports; one per pod
Pause containerSandbox container that holds the pod's namespaces
veth pairVirtual cable: one end in the pod (eth0), one on the node
CNIContainer Network Interface: spec + plugins for ADD/DEL/CHECK/STATUS/VERSION/GC
IPAMIP address management inside a CNI plugin
Pod CIDRAddress range for pods (cluster-wide and per node)
Service CIDR / ServiceCIDRRange ClusterIPs come from; also an API object
OverlayEncapsulating pod packets between nodes (VXLAN, Geneve, IP-in-IP)
VXLAN / GeneveUDP encapsulations (8472 / 6081 in Cilium)
Native routing / BGPRouting pod CIDRs without encapsulation
eBPFIn-kernel programs used by Cilium/Calico for the datapath
MTULargest packet a link carries; overlays reduce it
ServiceStable name + virtual IP for a set of pods
ClusterIPThe Service's virtual IP
EndpointSliceAPI object listing a Service's endpoints with conditions
Endpoints (API)Older, deprecated (v1.33) list of endpoints
ready / serving / terminatingEndpointSlice conditions
kube-proxyNode agent that programs Service rules
iptables / nftables / IPVS modekube-proxy backends
KUBE-SERVICES / KUBE-SVC / KUBE-SEPiptables chains: dispatch, per-Service, per-endpoint
KUBE-MARK-MASQMarks packets (0x4000) for masquerade
kube-proxy replacementCilium's eBPF implementation of Services
Maglev / DSRConsistent hashing; Direct Server Return (Cilium)
Session affinityClientIP stickiness, default timeout 10800 s
Headless ServiceclusterIP: None; DNS returns pod IPs
ExternalNameService that is a DNS CNAME
NodePortPort 30000-32767 on every node
LoadBalancerService type provisioned by a controller
loadBalancerClassSelects a non-default LB implementation
MetalLBBare-metal LB using ARP/NDP or BGP
Cloud Provider KINDLoadBalancer implementation for kind
AWS Load Balancer ControllerProvisions NLB/ALB for Services, Ingress, Gateway
externalTrafficPolicyCluster (SNAT, even) or Local (client IP, node-local)
healthCheckNodePortPort LBs probe for Local policy
internalTrafficPolicyNode-local endpoints for in-cluster traffic
Topology-aware routing / hintsZone-aware endpoint selection
trafficDistributionPreferSameZone, PreferSameNode (PreferClose deprecated)
CoreDNS / CorefileCluster DNS server and its config
ndotsDots threshold before a name is tried as absolute
dnsPolicyClusterFirst, Default, ClusterFirstWithHostNet, None
NodeLocal DNSCachePer-node DNS cache DaemonSet on a link-local IP
Ingress / IngressClassHTTP routing API (frozen) and its controller binding
Ingress controllerProxy implementing Ingress (ingress-nginx, Traefik, HAProxy, cloud)
Gateway APIGatewayClass, Gateway, HTTPRoute, GRPCRoute, ReferenceGrant
allowedRoutes / parentRefsGateway's attach policy / Route's attachment
NetworkPolicyLabel-based pod firewall API
podSelector / namespaceSelector / ipBlockNetworkPolicy peer selectors
AdminNetworkPolicyCluster-scoped, deny-capable policy API (CRD)
Egress gatewayNode(s) giving pods a predictable source IP
Masquerade / SNATRewriting the source to the node's address
conntrackKernel connection table behind NAT and Services
hostNetwork / hostPortUse the node netns / map one node port
Dual-stackIPv4 + IPv6 for pods and Services
Sidecar / REDIRECTMesh proxy in the pod; iptables capture to it
Ambient / ztunnel / waypointIstio sidecar-less mesh components
kubectl port-forwardAPI-server tunnel to one pod's TCP port
netshootDebug image with networking tools
kindKubernetes in Docker; nodes are containers

References ​

Every URL was fetched and its text saved under scratchpad/sources/kubernetes-networking/; the HTTP status was 200 when fetched. Kubernetes pages document v1.37.

Built by Morteza Negahi