Kubernetes Hour 3: Networking
- Explain the four basic requirements of the Kubernetes network model, and draw the Pod-to-Pod packet paths within a node and across nodes (veth, bridge/routing, overlay or native routing).
- Understand what a Service's virtual IP really is: how kube-proxy translates EndpointSlices into iptables or nftables rules, and how DNAT and conntrack do the load balancing.
- Read a Pod's
/etc/resolv.conf, explain the performance impact ofndots:5, and use a headless Service with a StatefulSet for stable service discovery. - Choose the right entry point for external traffic: NodePort, LoadBalancer (externalTrafficPolicy), Ingress or Gateway API. Be able to draft a migration plan for ingress-nginx.
- Use Gateway API v1.6 to implement path routing, header routing, canary weights, HTTPS termination and cross-namespace references.
- Use NetworkPolicy to build a zero-trust network for the shop app with “default deny plus minimal allow”. Be able to use a layered approach to locate any “cannot connect” problem.
1-hour timetable
| # | Time | Module | Core content | Animation / interactive | Lab (kind cluster) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up | Multi-node kind (kindnet ships with NetworkPolicy), kube-proxy in nftables mode, cloud-provider-kind, Gateway API CRDs + Envoy Gateway, redeploy shop | — | Rebuild the cluster + deploy shop |
| 1 | 00–07 | Network model and CNI | Four requirements, shared localhost inside a Pod, veth, cross-node routing, CNI ADD, IPAM, podCIDR, CNI comparison | Cross-node Pod-to-Pod packet path | Find the veth, routes and CNI config on a node |
| 2 | 07–15 | Service deep dive | ClusterIP virtual IP, three kube-proxy modes, EndpointSlice conditions, sessionAffinity, internalTrafficPolicy, trafficDistribution | Service DNAT load balancing + conntrack | Trace the api Service with nft list ruleset |
| 3 | 15–21 | CoreDNS and service discovery | resolv.conf, search/ndots, A/SRV, headless, StatefulSet DNS, ExternalName, dnsPolicy, NodeLocal DNSCache | search list expansion (type a short hostname) | dig for each record type |
| 4 | 21–28 | LoadBalancer and external traffic | NodePort range, CCM, Azure LB annotations, externalTrafficPolicy, healthCheckNodePort, loadBalancerSourceRanges | Cluster vs Local hops and SNAT comparison | cloud-provider-kind assigns an external IP; observe the source IP |
| 5 | 28–34 | Ingress and the ingress-nginx retirement | Ingress API still GA, IngressClass, pathType, TLS; ingress-nginx archived; ingress2gateway 1.0; AKS migration path | pathType matchers | Convert Ingress with ingress2gateway |
| 6 | 34–44 | Gateway API v1.6 | Role model, listeners, allowedRoutes, matches, filters, weighted canary, ReferenceGrant, GRPCRoute/TCPRoute, TLS, status | Request matching simulator (enter path/header) | /api→podinfo, /→nginx, 90/10, header routing |
| 7 | 44–52 | NetworkPolicy | Default allow, union semantics, selectors, default-deny, allow DNS, ClusterNetworkPolicy | Policy combinations → connection matrix | shop zero trust: web→api→db |
| 8 | 52–60 | Network troubleshooting | Layered approach, kubectl debug + netshoot, 7 common error types | Layered troubleshooting animation + interactive troubleshooting tree | Fault injection and diagnosis |
| — | After class | Cheat sheet · Capstone lab | Gateway + HTTPS + canary + zero trust + fault injection | Final quiz: 12 questions | Capstone lab |
Knowledge coverage matrix
| Target skills | Module | Key commands / objects | Lab | Quiz |
|---|---|---|---|---|
| Explain the Pod network model and the CNI call chain | m1 | ip route, /etc/cni/net.d, kubectl get node -o jsonpath='{..podCIDR}' | ✓ | ✓ |
| Read kube-proxy rules and EndpointSlices | m2 | nft list table ip kube-proxy, kubectl get endpointslices | ✓ | ✓ |
| Troubleshoot DNS resolution and ndots issues | m3 | dig, dnsConfig, Corefile | ✓ | ✓ |
| Expose a service and preserve the client source IP | m4 | type: LoadBalancer, externalTrafficPolicy: Local | ✓ | ✓ |
| Draft an ingress-nginx migration plan | m5 | ingress2gateway print --providers=ingress-nginx | ✓ | ✓ |
| Routing, TLS and canary with Gateway API | m6 | Gateway, HTTPRoute, ReferenceGrant | ✓ | ✓ |
| Build a default-deny zero-trust network | m7 | NetworkPolicy (ingress/egress, DNS allow) | ✓ | ✓ |
| Locate “cannot connect” problems layer by layer | m8 | kubectl debug --image=nicolaka/netshoot | ✓ | ✓ |
| AKS networking choices (Azure CNI Overlay / Cilium, internal LB, App Routing) | m1 m4 m5 | az aks create --network-plugin-mode overlay, LB annotations | Reading | ✓ |
Topics excluded from this hour
| Topic | Reason | Where to learn it |
|---|---|---|
| Service mesh (Istio / Linkerd, mTLS, ambient) | Cannot be covered properly in one hour; Gateway API comes first | Official Istio and Linkerd docs; AKS Istio add-on docs |
| IPv6 / dual-stack details | The lab environment uses IPv4 | kubernetes.io “IPv4/IPv6 dual-stack” |
| Automatic certificate issuance with cert-manager | This hour uses self-signed certificates to demonstrate TLS principles | hour 5 (security) / cert-manager.io |
| Cilium/Calico install tuning, BGP peering configuration, eBPF programming | Advanced platform engineering territory | docs.cilium.io, docs.tigera.io |
| RBAC splitting permissions for Gateway/Route | This hour only covers the role model | hour 5 (RBAC and hardening) |
| Full ingress deployment on AKS | Requires cloud resources and costs | AKS course hour 2 (networking) |
How to use this courseware
Theory · Diagrams · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Start with “Theory / Diagrams / Animation” to build a mental model, then do the “Lab”.
A module counts toward progress when you score ≥ 70% on its quiz or click “Mark this module complete”. Progress is saved in this browser's localStorage (key
k8s60-part3-progress-v1).The “Voice” tab uses the browser's built-in Web Speech API (en-US) to read the narration script aloud. If no English voice pack is installed, the script can still be read or passed to a TTS tool.
kindest/node:v1.37.0). Key changes: the kube-proxy nftables backend went GA in v1.33, and v1.37 switches to the netlink interface; the ipvs mode is deprecated (official docs expect it to be disabled by default in v1.40 and removed in v1.43); kube-dns is deprecated (migrate to CoreDNS); the ingress-nginx controller was archived on 2026-03-24 and no longer receives security patches (the Ingress API itself is still GA); Gateway API v1.6 moves TCPRoute/UDPRoute into the Standard channel. Gateway API v1.7.0 was released in 2026-10, but this hour pins v1.6.3 to match the compatibility requirements of Envoy Gateway v1.10.Module 0 · Warm-up (multi-node kind)
- Hours 1–2 completed: Azure VM
Standard_D4s_v5(Ubuntu 24.04, Docker Engine 29.x), withkindv0.33.0 andkubectl1.37 installed; Helm 4.x (helm version; if it is missing, install it with the official script from helm.sh). - Be familiar with the shop app:
web(nginx),api(podinfo 6.17.0, port 9898),db(postgres:17 StatefulSet). - All labs in this hour run on a local kind cluster and incur no cloud costs. The AKS content is for reading and comparison.
Why rebuild the cluster?
| Requirement | Cluster from hours 1–2 | This hour's approach (verified) |
|---|---|---|
| NetworkPolicy enforcement | kindnet (default CNI) | Starting with kind v0.24.0, kindnet supports NetworkPolicy out of the box via sigs.k8s.io/kube-network-policies (kind v0.24.0 release notes: “Out-of-the-box support for network policy”). kind v0.33.0 works by default, so there is no need to swap the CNI. Alternative: disableDefaultCNI: true + Calico v3.33.0. |
| kube-proxy mode | Default: iptables | networking.kubeProxyMode: nftables (kind supports iptables / nftables / ipvs / none), so you can learn the nftables backend that went GA in v1.33. The kube-proxy mode can only be set when the cluster is created, which is why a rebuild is needed. |
| type: LoadBalancer | EXTERNAL-IP stuck at <pending> | cloud-provider-kind: a CCM that runs on the host. It creates an Envoy container for each LoadBalancer Service and writes the IP back. |
| Gateway API | None | Gateway API v1.6.3 Standard CRDs + Envoy Gateway v1.10.0 (Helm) |
| trafficDistribution demo | No zone labels | Apply different topology.kubernetes.io/zone labels to the two workers |
Step 1: Delete the old cluster and rebuild it with the new config
kind delete cluster --name lab
cat > kind-lab-net.yaml <<'EOF'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: lab
networking:
kubeProxyMode: "nftables" # iptables | nftables | ipvs (deprecated) | none
podSubnet: "10.244.0.0/16" # kind default, written out here for reference
serviceSubnet: "10.96.0.0/16" # kind default
nodes:
- role: control-plane
- role: worker
labels:
topology.kubernetes.io/zone: zone-a
- role: worker
labels:
topology.kubernetes.io/zone: zone-b
EOF
kind create cluster --config kind-lab-net.yaml --image kindest/node:v1.37.0
kubectl get nodes -o wide
kubectl -n kube-system get configmap kube-proxy -o jsonpath='{.data.config\.conf}' | grep mode
NAME STATUS ROLES AGE VERSION INTERNAL-IP lab-control-plane Ready control-plane 60s v1.37.0 172.18.0.4 lab-worker Ready <none> 40s v1.37.0 172.18.0.2 lab-worker2 Ready <none> 40s v1.37.0 172.18.0.3 mode: nftables
kind (the user-defined bridge from module 5 of the Docker course), so node IPs look like 172.18.0.x. Pod IPs come from the podSubnet 10.244.0.0/16, and each node gets one /24 (spec.podCIDR).Alternative: disable kindnet and use Calico v3.33.0 (if you want to try Calico policies or BGP)
kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 name: lab networking: disableDefaultCNI: true podSubnet: 192.168.0.0/16 kubeProxyMode: "nftables" nodes: - role: control-plane - role: worker - role: worker
kind create cluster --config kind-lab-calico.yaml # Kubernetes 1.36 and later: kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.33.0/manifests/v3_projectcalico_org.yaml kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.33.0/manifests/tigera-operator.yaml kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.33.0/manifests/custom-resources.yaml # Or use the manifest method (choose one): # kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.33.0/manifests/calico.yaml kubectl get pods -A -w # wait for calico-node / calico-kube-controllers to be Running and nodes to become Ready
The CRD bundle is large, so the official guidance is to use kubectl create (apply may exceed the annotation size limit). Until the CNI is installed, nodes stay NotReady and CoreDNS stays Pending. This shows exactly why a Pod cannot get an IP without a CNI.
Step 2: cloud-provider-kind (so LoadBalancers actually get IPs)
# Option A: run as a container (README: images published at registry.k8s.io since v0.4.0) docker run -d --name cloud-provider-kind --restart unless-stopped \ --network kind -v /var/run/docker.sock:/var/run/docker.sock \ registry.k8s.io/cloud-provider-kind/cloud-controller-manager:v0.4.0 # Option B: go install (requires the Go toolchain) go install sigs.k8s.io/cloud-provider-kind@latest sudo install ~/go/bin/cloud-provider-kind /usr/local/bin cloud-provider-kind > /tmp/cpk.log 2>&1 & # kind labels the control plane to exclude it from external LBs; removing the label lets the control plane also serve as a backend (optional) kubectl label node lab-control-plane node.kubernetes.io/exclude-from-external-load-balancers-
Check the version number in the cloud-provider-kind README / Releases (at verification time, the README mentioned images from v0.4.0 onward; if a newer version exists, you can replace the tag). cloud-provider-kind uses the Docker socket to start one Envoy container per LoadBalancer Service, and the IP comes from the kind network.
Step 3: Gateway API v1.6.3 CRDs + Envoy Gateway v1.10.0
# ① Gateway API Standard channel CRDs (GatewayClass/Gateway/HTTPRoute/GRPCRoute/ReferenceGrant/TCPRoute/UDPRoute…) kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.3/standard-install.yaml kubectl get crd | grep gateway.networking.k8s.io # ② Install only Envoy Gateway's own CRDs (Gateway API CRDs are already managed by us; do not install two copies) helm template eg-crds oci://docker.io/envoyproxy/gateway-crds-helm --version v1.10.0 \ --set crds.gatewayAPI.enabled=false \ --set crds.envoyGateway.enabled=true \ | kubectl apply --server-side -f - # ③ Install the controller (turn off the CRD dependencies bundled with the chart) helm install eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 \ -n envoy-gateway-system --create-namespace --set crds.enabled=false kubectl wait --timeout=5m -n envoy-gateway-system deployment/envoy-gateway --for=condition=Available # ④ Create a GatewayClass (infrastructure provider role) kubectl apply -f - <<'EOF' apiVersion: gateway.networking.k8s.io/v1 kind: GatewayClass metadata: name: eg spec: controllerName: gateway.envoyproxy.io/gatewayclass-controller EOF kubectl get gatewayclass eg
NAME CONTROLLER ACCEPTED AGE eg gateway.envoyproxy.io/gatewayclass-controller True 5s
helm install?The Envoy Gateway docs explain that its Helm chart ships Gateway API CRDs from the Experimental channel by default. If the cluster's Gateway API CRDs are managed by you (or by a cloud provider such as AKS Managed Gateway API), install only Envoy Gateway's own CRDs: “do not mix them with another copy”. If the parameters differ from the current version's docs, follow Install with Helm.Step 4: Redeploy shop (full YAML)
Changes from hour 2: the namespace gets a label; api splits out a version label and adds api-v2 (for the canary); two version-specific Services, api-v1 and api-v2, are added; db uses a headless Service (module 3 covers DNS); and web's nginx reverse-proxies /api/ to api.
apiVersion: v1
kind: Namespace
metadata:
name: shop
labels:
app.kubernetes.io/part-of: shop
---
apiVersion: v1
kind: Secret
metadata:
name: db-secret
namespace: shop
type: Opaque
stringData:
POSTGRES_USER: shop
POSTGRES_PASSWORD: change-me-in-hour5
POSTGRES_DB: shop
---
apiVersion: v1
kind: ConfigMap
metadata:
name: web-nginx
namespace: shop
data:
default.conf: |
server {
listen 80;
location / {
default_type text/plain;
return 200 "shop web OK from $hostname\n";
}
location /api/ {
proxy_pass http://api.shop.svc.cluster.local:9898/;
}
}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: shop
spec:
replicas: 2
selector:
matchLabels: {app: web}
template:
metadata:
labels: {app: web, tier: frontend}
spec:
containers:
- name: nginx
image: nginx:1.29-alpine
ports:
- {name: http, containerPort: 80}
readinessProbe:
httpGet: {path: /, port: http}
resources:
requests: {cpu: 50m, memory: 32Mi}
limits: {memory: 128Mi}
volumeMounts:
- {name: conf, mountPath: /etc/nginx/conf.d}
volumes:
- name: conf
configMap: {name: web-nginx}
---
apiVersion: v1
kind: Service
metadata:
name: web
namespace: shop
spec:
selector: {app: web}
ports:
- {name: http, port: 80, targetPort: http}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-v1
namespace: shop
spec:
replicas: 3
selector:
matchLabels: {app: api, version: v1}
template:
metadata:
labels: {app: api, version: v1, tier: backend}
spec:
containers:
- name: podinfo
image: ghcr.io/stefanprodan/podinfo:6.17.0
command: ["./podinfo", "--port=9898", "--ui-message=shop api v1"]
ports:
- {name: http, containerPort: 9898}
readinessProbe:
httpGet: {path: /readyz, port: http}
livenessProbe:
httpGet: {path: /healthz, port: http}
resources:
requests: {cpu: 50m, memory: 64Mi}
limits: {memory: 128Mi}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-v2
namespace: shop
spec:
replicas: 1
selector:
matchLabels: {app: api, version: v2}
template:
metadata:
labels: {app: api, version: v2, tier: backend}
spec:
containers:
- name: podinfo
image: ghcr.io/stefanprodan/podinfo:6.17.0
command: ["./podinfo", "--port=9898", "--ui-message=shop api v2 (canary)"]
ports:
- {name: http, containerPort: 9898}
readinessProbe:
httpGet: {path: /readyz, port: http}
resources:
requests: {cpu: 50m, memory: 64Mi}
limits: {memory: 128Mi}
---
apiVersion: v1
kind: Service # Stable entry point: selects all versions (web reaches api through it)
metadata:
name: api
namespace: shop
spec:
selector: {app: api}
ports:
- {name: http, port: 9898, targetPort: http}
---
apiVersion: v1
kind: Service # Selects v1 only: used for weighted routing in the Gateway
metadata:
name: api-v1
namespace: shop
spec:
selector: {app: api, version: v1}
ports:
- {name: http, port: 9898, targetPort: http}
---
apiVersion: v1
kind: Service # Selects v2 only
metadata:
name: api-v2
namespace: shop
spec:
selector: {app: api, version: v2}
ports:
- {name: http, port: 9898, targetPort: http}
---
apiVersion: v1
kind: Service # headless: DNS returns Pod IPs directly; each StatefulSet Pod gets a stable DNS name
metadata:
name: db
namespace: shop
spec:
clusterIP: None
selector: {app: db}
ports:
- {name: postgres, port: 5432, targetPort: 5432}
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: db
namespace: shop
spec:
serviceName: db
replicas: 1
selector:
matchLabels: {app: db}
template:
metadata:
labels: {app: db, tier: data}
spec:
containers:
- name: postgres
image: postgres:17
envFrom:
- secretRef: {name: db-secret}
env:
- {name: PGDATA, value: /var/lib/postgresql/data/pgdata}
ports:
- {name: postgres, containerPort: 5432}
readinessProbe:
exec:
command: ["pg_isready", "-U", "shop", "-d", "shop"]
periodSeconds: 5
resources:
requests: {cpu: 100m, memory: 256Mi}
limits: {memory: 512Mi}
volumeMounts:
- {name: data, mountPath: /var/lib/postgresql/data}
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
kubectl apply -f shop.yaml kubectl -n shop rollout status deploy/web deploy/api-v1 deploy/api-v2 kubectl -n shop rollout status sts/db kubectl -n shop get pods -o wide kubectl -n shop get svc # A long-running debug client (with dig/curl/nc/tcpdump), reused throughout the course kubectl -n shop run netshoot --image=nicolaka/netshoot:v0.16 --labels=app=netshoot -- sleep infinity kubectl -n shop wait --for=condition=Ready pod/netshoot kubectl -n shop exec netshoot -- curl -s web/api/version
NAME READY STATUS IP NODE
api-v1-7c9d8b6f5-2xk4p 1/1 Running 10.244.1.5 lab-worker
api-v1-7c9d8b6f5-9qmzr 1/1 Running 10.244.2.4 lab-worker2
api-v1-7c9d8b6f5-tw8ld 1/1 Running 10.244.1.6 lab-worker
api-v2-5f6c7d9b8-h7n2c 1/1 Running 10.244.2.5 lab-worker2
db-0 1/1 Running 10.244.2.6 lab-worker2
web-6d8f9c7b4-l5kcz 1/1 Running 10.244.1.4 lab-worker
web-6d8f9c7b4-x2v9q 1/1 Running 10.244.2.3 lab-worker2
NAME TYPE CLUSTER-IP PORT(S)
api ClusterIP 10.96.142.17 9898/TCP
api-v1 ClusterIP 10.96.88.201 9898/TCP
api-v2 ClusterIP 10.96.30.115 9898/TCP
db ClusterIP None 5432/TCP
web ClusterIP 10.96.201.9 80/TCP
{
"commit": "…",
"version": "6.17.0"
}
kubectl config set-context --current --namespace=shop has already been run; across namespaces, -n is written explicitly. netshoot version v0.16 (updated on Docker Hub 2026-07-01).Module 1 · Network model and CNI
- Recite the four requirements of the Kubernetes network model, and explain “why Pods do not need NAT between them”.
- Explain how containers in a Pod share a network namespace (the same localhost), and the role of the pause/sandbox container.
- Draw Pod-to-Pod paths within a node and across nodes; compare overlay (VXLAN/Geneve) with native routing (BGP/cloud route tables).
- State when a CNI plugin is called: kubelet → CRI (containerd) → CNI
ADD, and how IPAM relates to podCIDR. - Compare the trade-offs of kindnet, Calico, Cilium (eBPF), Azure CNI Overlay and Azure CNI powered by Cilium.
What: the Kubernetes network model (four basic requirements)
| # | Requirement | Meaning | Compared with single-host Docker |
|---|---|---|---|
| 1 | Each Pod has its own IP | The Pod is the smallest unit of networking, and the IP belongs to the whole Pod (not to each container) | In Docker each container has an IP, but it is only valid within the local bridge |
| 2 | Pods reach each other without NAT | A Pod on any node can talk to another Pod directly by its Pod IP | Across hosts, you need -p port publishing (DNAT) |
| 3 | Nodes and Pods reach each other | Node agents (kubelet, system daemons) can reach all Pods on that node, and vice versa | The host can reach local containers |
| 4 | Consistent IPs | The IP a Pod sees for itself is the same IP other Pods see for it | After port mapping, the outside world sees the host IP |
Kubernetes defines these requirements but does not implement them. Implementation is left to CNI (Container Network Interface) plugins. Service virtual IPs (m2), DNS (m3) and policies (m7) all build on this flat Pod network.
Why: why a “flat, no-NAT” network?
- Transparent to apps: an app uses whatever port it listens on, with no port-mapping coordination. (On a single Docker host, the problem of 10 nginx containers competing for port 80 disappears.)
- Observability and security: the source IP inside the cluster is the real Pod IP, so NetworkPolicy can allow traffic based on Pod identity.
- Friendly to migration: Pods have their own IPs, like VMs, so legacy apps (such as protocols that carry IP addresses in their payload) also work.
How: following a Pod's creation to see how networking gets wired up
- The scheduler binds the Pod to a node → that node's kubelet watches the Pod.
- kubelet calls containerd's
RunPodSandboxthrough CRI: containerd creates the pause container (sandbox) and a new network namespace. - containerd reads the first config in
/etc/cni/net.d/(sorted by file name), runs the plugin binary under/opt/cni/bin/, and passes the environment variablesCNI_COMMAND=ADD,CNI_NETNSandCNI_IFNAME=eth0, with the JSON config on stdin. - The plugin: ① creates a veth pair, renames one end eth0 and moves it into the Pod netns, and leaves the other end on the host; ② calls an IPAM plugin (such as
host-local) to allocate an IP from the node'spodCIDR(for example 10.244.1.0/24); ③ configures the default route inside the Pod and the route on the host pointing to the Pod (or attaches it to a bridge); ④ returns the result as JSON (IP, gateway). - The Pod's application containers then join the same netns, so containers in a Pod share localhost and the port space (a sidecar reaches the main container at
127.0.0.1). When a Pod is deleted, kubelet → CRI → CNIDELreclaims the IP.
Across nodes: two main approaches
| Approach | How it works | Advantages | Costs | Examples |
|---|---|---|---|---|
| Overlay (encapsulation) | Pod-to-Pod packets are wrapped in UDP packets between nodes (VXLAN 4789 / Geneve 6081) | No requirements on the underlying network; works across subnets | About 50 bytes of encapsulation overhead per packet, so MTU must be lowered; packet capture is harder | Flannel VXLAN, Calico VXLAN, Cilium default tunnel, Azure CNI Overlay |
| Native routing | Pod subnets are routed directly between nodes: use static routes on the same L2 segment, and BGP or cloud route tables across L3 | No encapsulation, good performance, and Pod IPs are visible to the underlying network | Needs the underlying network to cooperate (BGP peering, route table limits) | kindnet (direct routing within the same Docker network), Calico BGP, Cilium native routing, AKS kubenet (UDR, a retired approach) |
When: how to choose a CNI
| CNI | Data plane | NetworkPolicy | Typical use case |
|---|---|---|---|
| kindnet | veth + node routes, IP masquerade | ✓ (since kind v0.24.0, based on kube-network-policies) | Local learning, CI |
| Calico (v3.33) | iptables/nftables or eBPF; BGP / VXLAN / IP-in-IP | ✓ + Calico extended policies (GlobalNetworkPolicy, tiers) | Self-managed or hybrid cloud that needs BGP interconnection with the enterprise network |
| Cilium | eBPF, can replace kube-proxy | ✓ + L7 policies (HTTP/gRPC/DNS FQDN), Hubble observability | Large scale, high performance, needs L7 observability |
| Azure CNI Overlay | Pod IPs come from a separate private CIDR, decoupled from the VNet | Must be paired with Azure NPM / Calico / Cilium | One of AKS's recommended defaults: saves VNet IPs |
| Azure CNI powered by Cilium | Azure IPAM + Cilium eBPF data plane | ✓ (implemented by Cilium) | On AKS when you need eBPF performance and Cilium policies |
--service-cluster-ip-range, and kube-proxy/eBPF implements them. The CNI only manages Pod IPs. ② “Two containers in the same Pod can listen on the same port”—no. They share a network namespace. ③ “Installing a CNI means you have NetworkPolicy”—not necessarily. Plugins such as Flannel do not enforce policies, and policy objects are silently ignored. ④ “Pod IPs are stable”—they change when a Pod is recreated, so use a Service or DNS for stable access.Architecture diagram: Pod networking in a kind cluster
Flow chart: CNI ADD call chain (how a Pod gets its IP)
Comparison: overlay encapsulation vs native routing
Step-by-step animation: cross-node packet from web Pod (lab-worker) to db-0 (lab-worker2)
Switch between “Native routing (kindnet) / Overlay (VXLAN)” to see the difference. The highlighted box shows the component currently handling the packet. The terminal shows real commands you can run on the node.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl get pods -o wide | View Pod IPs and their nodes | -l app=api, --field-selector spec.nodeName=lab-worker |
kubectl get nodes -o custom-columns=…podCIDR | Pod subnet assigned to each node | Assigned by kube-controller-manager --allocate-node-cidrs (some CNIs manage IPAM themselves, so this field may not be used) |
docker exec lab-worker ip route | View routes inside a kind node | On production nodes, use SSH or kubectl debug node/… |
ls /etc/cni/net.d /opt/cni/bin | CNI config and plugin binaries | The first conflist in file-name order takes effect |
crictl inspectp <podID> | View the sandbox's netns path and IP | Get the ID first with crictl pods --name web |
kubectl debug node/lab-worker -it --image=nicolaka/netshoot:v0.16 | Start a debug Pod in the node's netns (host root mounted at /host) | Works for managed nodes you cannot SSH into (AKS) |
kubectl get nodes -o custom-columns=NAME:.metadata.name,IP:.status.addresses[0].address,PODCIDR:.spec.podCIDR kubectl -n shop get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP,NODE:.spec.nodeName
NAME IP PODCIDR lab-control-plane 172.18.0.4 10.244.0.0/24 lab-worker 172.18.0.2 10.244.1.0/24 lab-worker2 172.18.0.3 10.244.2.0/24
docker exec lab-worker ip route docker exec lab-worker cat /etc/cni/net.d/10-kindnet.conflist docker exec lab-worker ls /opt/cni/bin
default via 172.18.0.1 dev eth0
10.244.0.0/24 via 172.18.0.4 dev eth0
10.244.1.4 dev veth3a1c2b4d scope host
10.244.1.5 dev veth9f0e7a12 scope host
10.244.2.0/24 via 172.18.0.3 dev eth0
172.18.0.0/16 dev eth0 proto kernel scope link src 172.18.0.2
{
"cniVersion": "0.4.0", "name": "kindnet",
"plugins": [ { "type": "ptp", "ipMasq": false,
"ipam": { "type": "host-local", "ranges": [[{"subnet": "10.244.1.0/24"}]] … } },
{ "type": "portmap", "capabilities": {"portMappings": true} } ]
}
How to verify:each local Pod has a /32 dev vethXXX route, and the /24 of each other node points to that node's IP. This is Figure 1-1. Common error: an empty /etc/cni/net.d → node NotReady (“cni plugin not initialized”). Production use: troubleshooting Pods stuck in ContainerCreating and running out of IP addresses. The exact conflist content varies by kindnet version, so follow the actual output.
kubectl -n shop run duo --image=nginx:1.29-alpine --overrides='{
"spec":{"containers":[
{"name":"nginx","image":"nginx:1.29-alpine"},
{"name":"sidecar","image":"nicolaka/netshoot:v0.16","command":["sleep","infinity"]}]}}'
kubectl -n shop wait --for=condition=Ready pod/duo
kubectl -n shop exec duo -c sidecar -- curl -sI http://127.0.0.1:80 | head -1
kubectl -n shop exec duo -c sidecar -- ip -br addr
kubectl -n shop delete pod duo
HTTP/1.1 200 OK lo UNKNOWN 127.0.0.1/8 ::1/128 eth0@if12 UP 10.244.1.9/24
Lab 1: Trace a Pod's network yourself (about 6 min)
POD=$(kubectl -n shop get pod -l app=web -o jsonpath='{.items[0].metadata.name}')
NODE=$(kubectl -n shop get pod $POD -o jsonpath='{.spec.nodeName}')
PIP=$(kubectl -n shop get pod $POD -o jsonpath='{.status.podIP}')
echo $POD $NODE $PIPkubectl -n shop debug -it $POD --image=nicolaka/netshoot:v0.16 --target=nginx -- sh -c 'ip -br link; ip route'
lo UNKNOWN eth0@if7 UP default via 10.244.1.1 dev eth0 10.244.1.1 dev eth0 scope link
eth0@if7 means the veth peer's ifindex on the host is 7.
docker exec $NODE ip -br link | awk '$0 ~ /^veth/ {print}' | head
docker exec $NODE sh -c "ip -o link | grep '^7:'"
docker exec $NODE ip route get $PIP
7: veth3a1c2b4d@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> … 10.244.1.4 dev veth3a1c2b4d src 10.244.1.1 uid 0
docker exec $NODE sh -c 'ls /var/lib/cni/networks/*/ 2>/dev/null | head'
Each file name is an allocated IP, and its content is the container ID. If the path does not exist, this kindnet version uses a different IPAM store; follow the actual output.
V2IP=$(kubectl -n shop get pod -l version=v2 -o jsonpath='{.items[0].status.podIP}')
kubectl -n shop exec netshoot -- curl -s $V2IP:9898/ | head -5
kubectl -n shop exec netshoot -- ip -4 -br addr show eth0
kubectl -n shop logs -l version=v2 --tail=3Case 1: VNet IP address exhaustion on AKS
Problem: in early “Azure CNI (Pod IPs from the VNet subnet)” clusters, each node reserved 30+ VNet IPs. When scaling to 200 nodes, the subnet ran out, and new nodes could not join.
Fix: new clusters switch to Azure CNI Overlay. Pod IPs come from a private CIDR unrelated to the VNet, so only nodes use VNet IPs. Traffic leaving the VNet is SNATed to the node IP.
az aks create -g rg-k8s-lab -n aks-lab \ --network-plugin azure --network-plugin-mode overlay \ --pod-cidr 192.168.0.0/16 \ --network-dataplane cilium # optional: Azure CNI powered by Cilium
Limitations: Pod IPs cannot be routed directly by the VNet or on-premises networks (use a LoadBalancer or Gateway when needed). Plugin migration has prerequisites, so follow the Microsoft Learn migration docs.
Case 2: Large packets hang over VXLAN + VPN (MTU)
Problem: a self-managed cluster runs across data centers over an IPsec VPN. curl to small endpoints works, but downloading large files or completing TLS handshakes hangs.
Cause: node MTU 1500 − IPsec overhead − 50 bytes for VXLAN, but Pods still send 1450-byte packets, and ICMP is blocked (PMTUD breaks).
Fix: set the MTU explicitly in the CNI (Calico: the Installation resource's spec.calicoNetwork.mtu; Cilium: --set MTU=…), or switch to native routing. Use a binary search with ping -M do -s 1400 to find the usable MTU.
Case 3: Service rules “disappear” after Cilium replaces kube-proxy
Problem: a new colleague ran iptables-save | grep KUBE-SVC on a node, found nothing, and assumed the Service was broken.
Explanation: Cilium's kube-proxy replacement implements Services with eBPF maps, so use cilium service list (or cilium-dbg) to inspect them. Confirming the cluster's data plane before troubleshooting is one of the first steps in the layered approach in m8.
Common errors and fixes
Warning FailedCreatePodSandBox … failed to setup network for sandbox: plugin type="…" failed (add): …
Cause: the CNI plugin's ADD failed: the plugin binary is missing, the config is wrong, the IPAM address pool is exhausted, or the CNI DaemonSet (kindnet/calico-node) is not ready.
kubectl describe pod <pod> | sed -n '/Events/,$p' kubectl -n kube-system get pods -o wide | grep -E 'kindnet|calico|cilium' docker exec lab-worker ls /etc/cni/net.d /opt/cni/bin docker exec lab-worker journalctl -u containerd --no-pager | grep -i cni | tail
Fix: restore the CNI DaemonSet. If addresses are exhausted, enlarge the podCIDR (usually requires a new cluster) or reduce maxPods per node.
node "lab-worker" status NotReady: container runtime network not ready: NetworkReady=false reason:NetworkPluginNotReady message:Network plugin returns error: cni plugin not initialized
Cause: the node has no CNI config yet (disableDefaultCNI: true is set but Calico is not installed, or the CNI Pod has crashed).
kubectl get nodes kubectl -n kube-system get ds kubectl -n calico-system get pods # Calico operator option
Fix: install or repair the CNI. CoreDNS will then move from Pending to Running.
Pods on different nodes time out when pinging each other; same-node pings work
Cause: missing routes between nodes (native routing mode), VXLAN UDP 4789 blocked by a security group or firewall, Calico BGP port 179 unreachable, or MTU mismatch.
docker exec lab-worker ip route | grep 10.244 kubectl -n shop exec netshoot -- traceroute -n <peer PodIP> docker exec lab-worker2 tcpdump -ni eth0 host <source PodIP> -c 5
Fix: allow the encapsulation/BGP ports between nodes; in the cloud, check the NSG and route tables; align the MTU.
One of the two containers in a Pod is in CrashLoopBackOff: bind: address already in use
Cause: containers in a Pod share the netns, and two containers listen on the same port (for example, a sidecar also listening on 8080).
Fix: change the listening port of one of the containers. Use kubectl debug … -- ss -lntp to see which container holds the port.
1. Write a command that lists the podCIDR of each node, and explain what can happen to this field when a CNI manages IPAM itself.
kubectl get nodes -o custom-columns=NAME:.metadata.name,PODCIDR:.spec.podCIDR
Calico (Calico IPAM), Cilium (cluster-pool), Azure CNI and others may not use spec.podCIDR, so Pod IPs may fall outside that range. Use the CNI's own IPAM objects instead (such as kubectl get ippools / ciliumnodes).
2. Without logging into the node, how do you find the host-side interface number of the veth peer for the web Pod's eth0?
kubectl -n shop debug -it <web-pod> --image=nicolaka/netshoot:v0.16 --target=nginx -- ip -br link
In the output, eth0@ifN: N is the host-side ifindex.
Your team needs to run 3,000 Pods on AKS. The VNet has only one /22 subnet left, and outbound traffic must be restricted by FQDN. Which networking option would you choose?
Choose Azure CNI Overlay + Cilium data plane (Azure CNI powered by Cilium). Overlay consumes only node IPs (a /22 has about 1,019 usable addresses, which is enough for the nodes), and Pods use a separate CIDR. Cilium provides eBPF performance and FQDN-style outbound policies. (Some advanced AKS networking features may need extra subscription or feature flags; follow Microsoft Learn.) Note that Pod IPs cannot be routed directly by the VNet, so inbound traffic goes through an LB/Gateway.
Verified teaching videos
The titles and channels above were verified through the YouTube oEmbed API (2026-11-15). Durations and publication dates could not be verified one by one, so they are not listed.
Official docs
- Services, Load Balancing, and Networking (network model)
- Networking add-ons list
- CNI Specification
- kind Configuration
Video storyboard script (for use with video generation tools)
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
Visual: two node boxes, each with two rounded Pod boxes labeled with IPs.
Narration: Kubernetes sets just four networking requirements. Every Pod has its own IP. Pods can reach each other without NAT. Nodes and Pods can reach each other. A Pod sees its own IP the same way other Pods see it.
Visual: zoom into one Pod. The pause container, nginx and the sidecar share a “netns” bubble, with lo and eth0 shown inside.
Narration: containers in the same Pod share a network namespace. So a sidecar can reach the main container on localhost, but the two cannot listen on the same port.
Visual: timeline animation kubelet → containerd → CNI ADD → a veth line connects the Pod to the host, and IPAM issues an IP tag from 10.244.1.0/24.
Narration: when a Pod is created, kubelet tells containerd through CRI to create the sandbox. containerd calls the CNI plugin's ADD command, and the plugin creates the veth, assigns the IP and writes the route.
Visual: a packet leaves the node on the left. In the split screen, the “native routing” packet arrives directly on the left, and the “VXLAN” packet on the right is wrapped in an outer envelope.
Narration: there are two ways to cross nodes. Native routing does not encapsulate, so it performs best, but the underlying network must know the Pod subnets. Overlay wraps the packet in UDP and needs nothing from the underlying network, but watch the MTU.
Visual: five CNI icon cards flip one after another: kindnet, Calico, Cilium, Azure CNI Overlay and Azure CNI powered by Cilium.
Narration: when choosing a CNI, look at three things: IP planning, whether you need network policy and Layer 7 features, and data plane performance.
Module 2 · Service deep dive: kube-proxy and EndpointSlice
- Explain why a
pingto a ClusterIP failing is normal, whilecurlworks. - Describe the control chain Service → EndpointSlice → kube-proxy → kernel rules, and the data path with DNAT + conntrack.
- Compare kube-proxy's iptables, nftables and ipvs modes and their lifecycles (the ipvs deprecation path).
- Read the
ready / serving / terminatingconditions of an EndpointSlice. Master sessionAffinity, internalTrafficPolicy and trafficDistribution.
What: a Service is a “stable virtual entry point”
A Service gives a set of Pods (selected by a selector) a stable ClusterIP and a DNS name. The kube-apiserver assigns the ClusterIP from the service CIDR (kind's default is 10.96.0.0/16). No network interface holds it. It exists only in the iptables/nftables rules (or eBPF maps) on each node. The rules match TCP/UDP/SCTP packets destined for “ClusterIP:port” and DNAT them to a backend Pod. ICMP does not match these rules, so pinging a ClusterIP usually fails, and that is normal.
Why: why EndpointSlices and kube-proxy are needed
| Component | Responsibility | Watches / writes |
|---|---|---|
| EndpointSlice controller (kube-controller-manager) | Generates EndpointSlices from the Service selector and Pod readiness (each slice holds up to 100 endpoints by default) | Watches Services and Pods → writes EndpointSlices |
| kube-proxy (DaemonSet on every node) | Translates Services + EndpointSlices into forwarding rules in the node's kernel | Watches Services and EndpointSlices → writes nftables/iptables |
| Kernel netfilter + conntrack | Performs DNAT for each new connection, records the mapping in conntrack, and automatically translates later packets and replies based on that record | — |
The legacy Endpoints API (v1 Endpoints) has been marked deprecated since v1.33 (using it produces a warning). New code should use discovery.k8s.io/v1 EndpointSlices.
How: the three Linux modes of kube-proxy
| Mode | Implementation | Scale characteristics | Status (v1.37) |
|---|---|---|---|
| iptables | KUBE-SERVICES → KUBE-SVC-xxx (jumps chosen by probability with statistic random) → KUBE-SEP-xxx (DNAT) | Rules are matched linearly, so updates and matching slow down as Services grow | Still the default (official docs: a future release will change the default to nftables) |
| nftables | Table ip kube-proxy: uses maps and verdict maps for a single lookup jump, and numgen random mod N picks the backend | Incremental updates and O(1) lookups, better at large scale; requires kernel ≥ 5.13 | GA (v1.33); v1.37 switches to the netlink interface for better performance |
| ipvs | Kernel IPVS virtual servers + a few iptables rules | Multiple scheduling algorithms | Deprecated. Official docs: disabled by default from v1.40 (you can temporarily re-enable it with the KubeProxyIPVS feature gate), and removed in v1.43. Migrating to nftables is recommended. |
Note the behavior differences in nftables mode (official docs): NodePort is by default reachable only on the node's primary IP (--nodeport-addresses primary), 127.0.0.1:NodePort is not supported (it can be enabled with the v1.37 Alpha feature gate), and firewall allow rules are not added automatically for NodePort.
How: traffic policy fields
| Field | Values | Purpose |
|---|---|---|
sessionAffinity | None (default) / ClientIP | Pins the same client IP to the same backend; sessionAffinityConfig.clientIP.timeoutSeconds defaults to 10800 (3 hours) |
internalTrafficPolicy | Cluster (default) / Local | Local: forwards only to ready endpoints on this node; if this node has no endpoints, traffic is dropped (suited to DaemonSet-style local proxies). GA v1.26 |
trafficDistribution | PreferSameZone, PreferSameNode, PreferClose (deprecated; an older alias for PreferSameZone) | A “preference” rather than a hard requirement: prefers endpoints in the same zone or on the same node, and falls back to a wider scope when none exist. Reduces cross-AZ data transfer costs and lowers latency. For the feature stage of each value, check the official docs. |
publishNotReadyAddresses | true/false | Also publishes not-ready Pods to DNS and endpoints (commonly used for StatefulSet cluster self-discovery) |
EndpointSlice conditions
| Condition | Meaning | How kube-proxy uses it |
|---|---|---|
ready | Pod is ready (readinessProbe passing) and not terminating | Normal traffic goes only to ready=true |
serving | Readiness probe passing (regardless of termination) | A terminating Pod with serving=true can still receive traffic when there are no ready endpoints (fallback for graceful termination) |
terminating | Pod has a deletionTimestamp | New connections are no longer preferentially sent to it; existing connections continue (conntrack) |
When: which Service type to use
| Type | When to use |
|---|---|
| ClusterIP | Cluster-internal service (default) |
| Headless (clusterIP: None) | Need direct Pod IPs: StatefulSets, client-side load balancing (gRPC) |
| NodePort / LoadBalancer | Expose L4 externally (Module 4) |
| ExternalName | Give an external domain a cluster-internal alias (Module 3) |
Architecture diagram: control plane (what writes the rules) and data plane (what forwards the traffic)
Data-flow diagram: DNAT and return traffic for one TCP connection
Step-by-step animation: Service DNAT load balancing (nftables mode)
Play to watch a new connection; click “Start 20 new connections” to see the random distribution; click “Remove one endpoint” to simulate a readiness failure and kube-proxy rewriting the rules.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl get svc api -o wide | ClusterIP, ports, selector | -o yaml to see fields such as trafficPolicy |
kubectl get endpointslices -l kubernetes.io/service-name=api | The Service's actual backends | -o yaml to see conditions, nodeName, zone |
kubectl -n kube-system get cm kube-proxy -o jsonpath='{.data.config\.conf}' | grep mode | Current kube-proxy mode | An empty string means the default (iptables) |
docker exec lab-worker nft list table ip kube-proxy | nftables-mode rules | Or nft list ruleset |
docker exec lab-worker iptables-save | grep KUBE-SVC | iptables-mode rules | Nearly empty in nftables mode |
docker exec lab-worker conntrack -L -d 10.96.142.17 | View a Service's connection mapping | If the node image has no conntrack tool, use kubectl debug node/… + netshoot |
kubectl -n kube-system get configmap kube-proxy -o jsonpath='{.data.config\.conf}' | grep mode
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api -o wide
mode: nftables NAME ADDRESSTYPE PORTS ENDPOINTS AGE api-7xkqp IPv4 9898 10.244.1.5,10.244.2.4,10.244.1.6 + 1 more… 20m
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api \
-o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]}{"\t"}{.nodeName}{"\t"}{.zone}{"\t"}{.conditions}{"\n"}{end}'
10.244.1.5 lab-worker zone-a {"ready":true,"serving":true,"terminating":false}
10.244.2.4 lab-worker2 zone-b {"ready":true,"serving":true,"terminating":false}
10.244.1.6 lab-worker zone-a {"ready":true,"serving":true,"terminating":false}
10.244.2.5 lab-worker2 zone-b {"ready":true,"serving":true,"terminating":false}
docker exec lab-worker nft list chain ip kube-proxy services docker exec lab-worker sh -c "nft list table ip kube-proxy | grep -A3 'service-.*shop/api/tcp/http'"
table ip kube-proxy {
chain services {
ip daddr . meta l4proto . th dport vmap @service-ips
…
}
}
chain service-ULMVA6XW-shop/api/tcp/http {
ip daddr 10.96.142.17 tcp dport 9898 ip saddr != 10.244.0.0/16 jump mark-for-masquerade
numgen random mod 4 vmap { 0 : goto endpoint-5OJB2KTY-shop/api/tcp/http__10.244.1.5/9898, 1 : goto endpoint-…, 2 : goto endpoint-…, 3 : goto endpoint-… }
}
chain endpoint-5OJB2KTY-shop/api/tcp/http__10.244.1.5/9898 {
ip saddr 10.244.1.5 jump mark-for-masquerade
meta l4proto tcp dnat to 10.244.1.5:9898
}
How to verify: the N in mod N should equal the number of ready endpoints; scale api-v1 down to 1 and check again, and N becomes 2. Common mistake: using iptables-save to inspect rules in an nftables cluster and concluding the Service is not working. Production use: tell apart “endpoints exist but rules are not updated” (a kube-proxy problem) from “the endpoints do not exist” (a selector or readiness problem). ip saddr 10.244.1.5 jump mark-for-masquerade is hairpin traffic: when a Pod reaches itself through a Service, SNAT is required.
docker exec lab-worker sh -c 'iptables-save -t nat | grep -E "KUBE-SVC|KUBE-SEP" | grep shop/api | head'
-A KUBE-SERVICES -d 10.96.142.17/32 -p tcp -m comment --comment "shop/api:http cluster IP" -m tcp --dport 9898 -j KUBE-SVC-XXXX -A KUBE-SVC-XXXX -m comment --comment "shop/api:http -> 10.244.1.5:9898" -m statistic --mode random --probability 0.25000000000 -j KUBE-SEP-AAAA -A KUBE-SEP-AAAA -p tcp -m tcp -j DNAT --to-destination 10.244.1.5:9898
apiVersion: v1
kind: Service
metadata:
name: api
namespace: shop
spec:
selector: {app: api}
ports:
- {name: http, port: 9898, targetPort: http}
trafficDistribution: PreferSameZone # prefer endpoints in the same zone
# internalTrafficPolicy: Local # use only endpoints on this node (drop if none)
# sessionAffinity: ClientIP
# sessionAffinityConfig: {clientIP: {timeoutSeconds: 600}}
Lab 2: Trace a ClusterIP all the way to a Pod (about 8 minutes)
CIP=$(kubectl -n shop get svc api -o jsonpath='{.spec.clusterIP}')
kubectl -n shop exec netshoot -- ping -c 2 -W 1 $CIP # usually times out: no rule matches ICMP
kubectl -n shop exec netshoot -- curl -s -m 3 $CIP:9898/version # succeeds
docker exec lab-worker ip addr | grep $CIP || echo "no interface holds $CIP"/ returns hostname.
kubectl -n shop exec netshoot -- sh -c 'for i in $(seq 1 20); do curl -s api:9898/ | grep -o "\"hostname\": \"[^\"]*\""; done | sort | uniq -c'
6 "hostname": "api-v1-7c9d8b6f5-2xk4p" 5 "hostname": "api-v1-7c9d8b6f5-9qmzr" 4 "hostname": "api-v1-7c9d8b6f5-tw8ld" 5 "hostname": "api-v2-5f6c7d9b8-h7n2c"
/readyz/disable endpoint to make one Pod not ready.
V2=$(kubectl -n shop get pod -l version=v2 -o jsonpath='{.items[0].metadata.name}')
V2IP=$(kubectl -n shop get pod $V2 -o jsonpath='{.status.podIP}')
kubectl -n shop exec netshoot -- curl -s -X POST $V2IP:9898/readyz/disable
sleep 15
kubectl -n shop get pod $V2 # READY 0/1, but STATUS Running and RESTARTS 0
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api -o yaml | grep -B2 -A3 "$V2IP"
docker exec lab-worker sh -c "nft list table ip kube-proxy | grep 'numgen.*shop/api/tcp/http'"
api-v2-5f6c7d9b8-h7n2c 0/1 Running 0 25m
- addresses: ["10.244.2.5"]
conditions: {ready: false, serving: false, terminating: false}
numgen random mod 3 vmap { … }
Restore: kubectl -n shop exec netshoot -- curl -s -X POST $V2IP:9898/readyz/enable.
PreferSameZone to api. Requests from a client in zone-a should hit only the endpoints in zone-a (lab-worker).
kubectl -n shop patch svc api -p '{"spec":{"trafficDistribution":"PreferSameZone"}}'
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api -o yaml | grep -A2 hints
kubectl -n shop run za --image=nicolaka/netshoot:v0.16 --overrides='{"spec":{"nodeSelector":{"topology.kubernetes.io/zone":"zone-a"}}}' -- sleep infinity
kubectl -n shop wait --for=condition=Ready pod/za
kubectl -n shop exec za -- sh -c 'for i in $(seq 1 10); do curl -s api:9898/ | grep -o "api-v[12]-[a-z0-9-]*"; done | sort | uniq -c'
hints:
forZones:
- name: zone-a
5 api-v1-7c9d8b6f5-2xk4p
5 api-v1-7c9d8b6f5-tw8ldkubectl -n shop patch svc api -p '{"spec":{"sessionAffinity":"ClientIP"}}'
kubectl -n shop exec netshoot -- sh -c 'for i in $(seq 1 5); do curl -s api:9898/ | grep -o "api-v[12]-[a-z0-9-]*"; done'
All 5 requests hit the same Pod.
kubectl -n shop patch svc api --type=json -p '[{"op":"remove","path":"/spec/trafficDistribution"},{"op":"replace","path":"/spec/sessionAffinity","value":"None"}]'
kubectl -n shop delete pod za
kubectl -n shop exec netshoot -- curl -s -X POST $V2IP:9898/readyz/enableCase 1: gRPC service has “uneven load”
Problem: the order service calls the pricing service (gRPC) through a ClusterIP. After scaling to 10 Pods, CPU is still concentrated on 2 of them.
Cause: a Service load-balances per connection at L4. gRPC clients keep a small number of long-lived HTTP/2 connections, and all requests are multiplexed over those connections.
Approach: ① switch to a headless Service with gRPC client-side load balancing (dns:///pricing-headless:50051, round_robin); ② or do L7 load balancing through the Gateway API GRPCRoute or a service mesh; ③ set MaxConnectionAge on the server so connections are periodically rebuilt.
Case 2: migrating a large cluster from iptables to nftables
Problem: in a cluster with 8,000 Services, each rolling release takes kube-proxy several seconds to sync rules, and new endpoints are unreachable during that time.
Approach: first verify on one node pool that the kernel is 5.13 or later; set mode: nftables in the kube-proxy config and do a rolling restart of kube-proxy (kube-proxy cleans up leftover rules from the previous mode). Do this in a maintenance window and watch sync_proxy_rules_duration_seconds. Note that NodePort is reachable only on the primary IP, and the host firewall must allow it.
Limit: on managed clusters (such as AKS), the platform controls the kube-proxy mode. Check the cloud provider's docs to see whether it can be configured.
Case 3: cross-availability-zone traffic costs
Problem: in a cluster spanning three AZs, 2/3 of service-to-service calls cross AZs, and monthly data transfer costs are high.
Approach: set trafficDistribution: PreferSameZone on high-traffic internal services, and make sure every zone has enough replicas (together with topologySpreadConstraints). Limit: a zone with too few replicas can be overloaded. This is a “preference”, and it does not balance load automatically by capacity.
Common errors and fixes
curl: (7) Failed to connect to api port 9898: Connection refused (EndpointSlice is empty)
Cause: the Service selector does not match the Pod labels, or all Pods are not ready. nftables and iptables reject traffic directly for a Service with no endpoints.
kubectl -n shop get svc api -o jsonpath='{.spec.selector}'; echo
kubectl -n shop get pods --show-labels -l app=api
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api
Fix: correct the selector and labels; fix the readinessProbe.
curl: (28) Connection timed out after 3000 milliseconds (endpoints exist)
Cause: wrong targetPort (it points to a port the container is not listening on), the app listens only on 127.0.0.1, a NetworkPolicy blocks the traffic, or the cross-node Pod network is failing.
kubectl -n shop get svc api -o jsonpath='{.spec.ports}'; echo
EP=$(kubectl -n shop get endpointslices -l kubernetes.io/service-name=api -o jsonpath='{.items[0].endpoints[0].addresses[0]}')
kubectl -n shop exec netshoot -- curl -s -m 3 $EP:9898/healthz # bypass the Service and connect directly to the Pod
kubectl -n shop get networkpolicy
Fix: if a direct connection to the Pod succeeds, the problem is the port mapping in the Service. If a direct connection also fails, the problem is the Pod itself or the network/policy (Module 7, Module 8).
Warning: v1 Endpoints is deprecated in v1.33+; use discovery.k8s.io/v1 EndpointSlice
Cause: a script or controller is still reading and writing the old Endpoints API.
Fix: switch to kubectl get endpointslices -l kubernetes.io/service-name=NAME; migrate custom controllers to an EndpointSlice informer.
After changing a Service to internalTrafficPolicy: Local, Pods on some nodes time out
Cause: under the Local policy, traffic is dropped when the client's node has no local endpoints (the official docs state this explicitly).
Fix: use Local only for DaemonSet-style services. For regular services, use trafficDistribution: PreferSameNode instead (it has a fallback).
1. Write the command that lists the IPs, the node, and the ready state of every endpoint of the api Service.
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api \
-o jsonpath='{range .items[*].endpoints[*]}{.addresses[0]} {.nodeName} {.conditions.ready}{"\n"}{end}'2. On a kind node in nftables mode, how do you confirm how many backends are currently taking part in load balancing for the api Service?
docker exec lab-worker sh -c "nft list table ip kube-proxy | grep 'numgen.*shop/api/tcp/http'"
The N in numgen random mod N is the number of ready endpoints.
During a rolling release, clients occasionally get 502 errors. The old Pod received SIGTERM and exited immediately, but requests were still forwarded to it. What is the cause, and how would you improve this?
Endpoint removal is asynchronous. The Pod enters terminating, then the EndpointSlice is updated, then each node's kube-proxy updates its rules. There is a propagation delay of a few seconds. If the app closes its listener as soon as it gets SIGTERM, new connections are sent to a closed port. Improvements: ① add a short preStop sleep in the container (for example 5–10 seconds, or use the built-in lifecycle.preStop.sleep action; check the official docs for its feature stage); ② shut the app down gracefully: stop accepting new connections and finish in-flight requests; ③ make terminationGracePeriodSeconds longer than the preStop time plus the drain time; ④ use the serving and terminating conditions of EndpointSlice for a graceful fallback.
Verified teaching videos
Titles and channels were verified via YouTube oEmbed. No verified video specifically covering the nftables backend was found.
Official docs
Video storyboard script
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
On screen: in the terminal, ping 10.96.142.17 times out while curl beside it succeeds, and question marks appear on screen.
Narration: Why can curl reach a ClusterIP but ping can't? Because a ClusterIP isn't a network interface. It's a set of forwarding rules in the kernel.
On screen: Service and Pod icons flow into the EndpointSlice controller, which produces an “endpoint list.” Kube-proxy on the three nodes then reads that list.
Narration: The EndpointSlice controller builds the endpoint list from the selector and readiness state. Each node's kube-proxy watches that list and writes it out as local nftables rules.
On screen: a packet hits the nft rule table, a die rolls and picks the third backend, the destination address label on the packet is rewritten, and the conntrack ledger records one line.
Narration: The first packet of a new connection is randomly assigned a backend and gets destination NAT. Conntrack remembers the mapping, and return packets are translated back to the ClusterIP automatically.
On screen: three mode cards: iptables (long chains), nftables (table lookup), and ipvs (stamped “deprecated”).
Narration: In version 1.37, iptables is still the default. nftables is now officially available and better suited to large clusters. ipvs is deprecated and planned for removal in version 1.43.
Module 3 · CoreDNS and Service Discovery
- Read a Pod's
/etc/resolv.conf: nameserver, search domains, andndots:5, and estimate the number of requests a single lookup makes. - Understand Service A, AAAA, and SRV records, headless Services returning Pod IPs, and the stable per-Pod domain names of StatefulSets.
- Use ExternalName,
dnsPolicy(ClusterFirst/Default/ClusterFirstWithHostNet/None), anddnsConfig. - Understand what each plugin in the CoreDNS Corefile does, and know when to introduce NodeLocal DNSCache.
What: what cluster DNS is
Cluster DNS is CoreDNS running as a Deployment, fronted by a Service named kube-dns. Its ClusterIP is usually the 10th address in the service CIDR, which is 10.96.0.10 in kind. The name and the label k8s-app=kube-dns are kept for compatibility with the earlier kube-dns implementation. The kube-dns implementation itself was deprecated in v1.37, so clusters still using kube-dns should migrate to CoreDNS. The kubelet writes /etc/resolv.conf into each container when it creates the Pod, based on dnsPolicy.
search shop.svc.cluster.local svc.cluster.local cluster.local nameserver 10.96.0.10 options ndots:5
Why: search and ndots make short names work, but they carry a performance cost
Rule: when a name has fewer dots than ndots (5), the resolver first appends each search domain in turn and queries them, and only queries the original name after all of them fail. A name with 5 or more dots, or one ending in . (an FQDN), is queried directly.
| Query name | Dots | Actual queries in order (each also queries A and AAAA separately) | Result |
|---|---|---|---|
api | 0 | api.shop.svc.cluster.local ✓ | Hit in round 1 |
db.shop | 1 | db.shop.shop.svc… ✗ → db.shop.svc.cluster.local ✓ | 2 rounds |
login.microsoftonline.com | 2 | …shop.svc.cluster.local ✗ → …svc.cluster.local ✗ → …cluster.local ✗ → login.microsoftonline.com ✓ | 4 rounds × (A+AAAA) = 8 queries |
login.microsoftonline.com. | FQDN | Direct query | 1 round |
On cloud nodes, resolv.conf may also append a cloud provider's domain to search (for example Azure's xxx.internal.cloudapp.net), which adds more rounds.
How: record types
| Object | Record | Example |
|---|---|---|
| Regular Service | A/AAAA → ClusterIP | api.shop.svc.cluster.local → 10.96.142.17 |
| Named Service port | SRV _port-name._protocol.service.namespace.svc.cluster.local | _http._tcp.api.shop.svc.cluster.local → 0 100 9898 api.shop.svc.cluster.local. |
| Headless Service | A → the IP of each ready Pod (multiple records) | db.shop.svc.cluster.local → 10.244.2.6 |
| StatefulSet Pod (serviceName points to a headless Service) | A: <pod>.<svc>.<ns>.svc.cluster.local | db-0.db.shop.svc.cluster.local (the name stays the same after the Pod is recreated) |
| ExternalName | CNAME | pay.shop.svc.cluster.local → CNAME api.example.com |
| Reverse | PTR | Reverse lookup of Service IPs and Pod IPs (in-addr.arpa) |
How: dnsPolicy and dnsConfig
| dnsPolicy | resolv.conf source | Purpose |
|---|---|---|
| ClusterFirst (the Pod default) | Cluster DNS plus search domains. Non-cluster names are forwarded to the upstream by CoreDNS. | Most Pods |
| Default (note: it is not the default!) | Inherits the node's resolv.conf | System components that don't need cluster service discovery |
| ClusterFirstWithHostNet | Same as ClusterFirst | Required for Pods with hostNetwork: true that want to use cluster DNS |
| None | Specified entirely by dnsConfig | Custom nameserver, search, and options |
spec:
dnsPolicy: ClusterFirst
dnsConfig:
options:
- name: ndots
value: "2"
- name: single-request-reopen # glibc option; musl (alpine) ignores it
How: CoreDNS Corefile and NodeLocal DNSCache
The CoreDNS configuration lives in the kube-system/coredns ConfigMap and is made of a plugin chain: kubernetes (watches Services and EndpointSlices to generate records), forward (forwards non-cluster domains to the upstream, by default the node's resolv.conf), cache, loop (detects forwarding loops), reload (reloads automatically when the ConfigMap changes), loadbalance (shuffles the order of multiple A records), and prometheus :9153.
NodeLocal DNSCache: a per-node DaemonSet caching proxy that listens on a link-local address (commonly 169.254.20.10). Pod DNS queries go to the local node's cache first. This avoids UDP contention in the conntrack table and cross-node hops, and significantly reduces DNS latency and CoreDNS load. Recommended for large clusters and DNS-heavy applications.
When: when you need to tune DNS
- An app makes many lookups of external domains (SaaS APIs, database FQDNs): use a trailing dot in the name in code or config, or lower ndots.
- P99 DNS latency occasionally hits 5 seconds: this is typically a conntrack race or UDP packet loss. Consider NodeLocal DNSCache.
- Need to resolve internal corporate domains: add a separate
forwardfor that domain in the Corefile, pointing to the corporate DNS (on AKS, use thecoredns-customConfigMap).
getent hosts.Architecture diagram: one in-cluster DNS query
Flow diagram: differences in DNS answers between headless and regular Services
Interactive demo: how the search list expands (ndots)
Enter a name, choose ndots, and click “Resolve”. This shows the query order of the glibc resolver. Green means CoreDNS returned NOERROR; red means NXDOMAIN. Names that exist in the cluster: api, web, db, db-0.db, kube-dns.kube-system. Everything else is treated as an external domain.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl exec POD -- cat /etc/resolv.conf | View a Pod's DNS configuration | Confirm nameserver, search, and ndots |
dig +search +short api | Resolve using the search list (in netshoot) | By default, dig does not use search. Add +search. +ndots=5 sets it explicitly. |
dig SRV _http._tcp.api.shop.svc.cluster.local | Query SRV | The Service port needs a name |
getent hosts api | Resolve with libc behavior (closest to applications) | alpine (musl) behaves slightly differently |
kubectl -n kube-system get cm coredns -o yaml | Corefile | After a change, the reload plugin takes effect automatically (within about 30 seconds) |
kubectl -n kube-system logs -l k8s-app=kube-dns | CoreDNS logs | Adding the log plugin in the Corefile records every query (for temporary troubleshooting only) |
kubectl apply -f https://k8s.io/examples/admin/dns/dnsutils.yaml | Official DNS debug Pod | Image registry.k8s.io/e2e-test-images/agnhost:2.39 (the version used in the official docs) |
kubectl -n shop exec netshoot -- cat /etc/resolv.conf kubectl -n shop exec netshoot -- dig +search +short api kubectl -n shop exec netshoot -- dig +short db.shop.svc.cluster.local kubectl -n shop exec netshoot -- dig +short db-0.db.shop.svc.cluster.local kubectl -n shop exec netshoot -- dig +short SRV _http._tcp.api.shop.svc.cluster.local kubectl -n shop exec netshoot -- dig +short -x 10.96.0.10
search shop.svc.cluster.local svc.cluster.local cluster.local nameserver 10.96.0.10 options ndots:5 10.96.142.17 10.244.2.6 10.244.2.6 0 100 9898 api.shop.svc.cluster.local. kube-dns.kube-system.svc.cluster.local.
How to verify: a regular Service returns a VIP, and a headless Service returns Pod IPs. Common mistake: concluding that DNS is broken because dig api (without +search) returns NXDOMAIN. Production use: confirming service discovery and StatefulSet member addresses.
kubectl -n kube-system get configmap coredns -o jsonpath='{.data.Corefile}'
.:53 {
errors
health {
lameduck 5s
}
ready
kubernetes cluster.local in-addr.arpa ip6.arpa {
pods insecure
fallthrough in-addr.arpa ip6.arpa
ttl 30
}
prometheus :9153
forward . /etc/resolv.conf {
max_concurrent 1000
}
cache 30
loop
reload
loadbalance
}
apiVersion: v1 kind: Service metadata: name: payments namespace: shop spec: type: ExternalName externalName: api.example.com # CNAME only; the HTTP Host header and TLS SNI are still payments…, see Troubleshooting
Lab 3: Dig into everything (about 6 minutes)
kubectl -n shop exec netshoot -- dig +noall +answer api.shop.svc.cluster.local kubectl -n shop exec netshoot -- dig +noall +answer db.shop.svc.cluster.local kubectl -n shop scale sts db --replicas=2 && kubectl -n shop rollout status sts/db kubectl -n shop exec netshoot -- dig +noall +answer db.shop.svc.cluster.local kubectl -n shop exec netshoot -- dig +short db-1.db.shop.svc.cluster.local
api.shop.svc.cluster.local. 30 IN A 10.96.142.17 db.shop.svc.cluster.local. 30 IN A 10.244.2.6 db.shop.svc.cluster.local. 30 IN A 10.244.2.6 db.shop.svc.cluster.local. 30 IN A 10.244.1.10 10.244.1.10
After the lab, scale back: kubectl -n shop scale sts db --replicas=1. The db-1 PVC is kept and is deleted in the cleanup step.
kubectl -n shop create service externalname payments --external-name=www.kubernetes.io kubectl -n shop exec netshoot -- dig +noall +answer payments.shop.svc.cluster.local
payments.shop.svc.cluster.local. 30 IN CNAME www.kubernetes.io. www.kubernetes.io. … IN CNAME … … IN A …
kubectl -n kube-system get cm coredns -o yaml > coredns-backup.yaml
kubectl -n kube-system get cm coredns -o jsonpath='{.data.Corefile}' | sed 's/^\(\s*\)errors/\1errors\n\1log/' > Corefile
kubectl -n kube-system create cm coredns --from-file=Corefile --dry-run=client -o yaml | kubectl apply -f -
sleep 40
kubectl -n shop exec netshoot -- getent hosts www.kubernetes.io > /dev/null
kubectl -n shop exec netshoot -- getent hosts www.kubernetes.io. > /dev/null
kubectl -n kube-system logs -l k8s-app=kube-dns --since=1m | grep kubernetes.io
[INFO] 10.244.1.8:40112 - "A IN www.kubernetes.io.shop.svc.cluster.local. udp …" NXDOMAIN … [INFO] 10.244.1.8:40112 - "AAAA IN www.kubernetes.io.shop.svc.cluster.local. udp …" NXDOMAIN … [INFO] 10.244.1.8:51533 - "A IN www.kubernetes.io.svc.cluster.local. udp …" NXDOMAIN … [INFO] 10.244.1.8:51533 - "AAAA IN www.kubernetes.io.svc.cluster.local. udp …" NXDOMAIN … [INFO] … "A IN www.kubernetes.io.cluster.local. …" NXDOMAIN … [INFO] … "AAAA IN www.kubernetes.io.cluster.local. …" NXDOMAIN … [INFO] … "A IN www.kubernetes.io. …" NOERROR … [INFO] … "AAAA IN www.kubernetes.io. …" NOERROR … [INFO] … "A IN www.kubernetes.io. …" NOERROR … ← second query (FQDN) has only these two lines [INFO] … "AAAA IN www.kubernetes.io. …" NOERROR …
kubectl -n shop run nd2 --image=nicolaka/netshoot:v0.16 --overrides='{"spec":{"dnsConfig":{"options":[{"name":"ndots","value":"2"}]}}}' -- sleep infinity
kubectl -n shop wait --for=condition=Ready pod/nd2
kubectl -n shop exec nd2 -- cat /etc/resolv.conf
kubectl -n shop exec nd2 -- getent hosts api # short names still workkubectl apply -f coredns-backup.yaml kubectl -n shop delete pod nd2; kubectl -n shop delete svc payments kubectl -n shop scale sts db --replicas=1; kubectl -n shop delete pvc data-db-1
Case 1: occasional 5-second P99 latency when calling Azure SQL
Problem: a .NET service accesses xxx.database.windows.net. Most requests are fine, but occasionally there is a 5-second delay.
Diagnosis: CoreDNS logs show that each lookup first produces 3–4 groups of NXDOMAIN. The node's conntrack statistics show insert_failed increasing (a race when concurrent A/AAAA UDP queries use the same source port). After packet loss, the resolver retries after 5 seconds.
Approach: ① change the connection string to an FQDN with a trailing dot, or set ndots: 2 on the Pod; ② enable NodeLocal DNSCache (on AKS, follow the currently supported method in Microsoft Learn); ③ enable connection pooling in the app to reduce repeated lookups.
Case 2: AKS resolving internal corporate domains
Problem: Pods need to resolve corp.contoso.com, which exists only on the local DNS server.
Approach: AKS does not allow editing the coredns ConfigMap directly. Instead, use the coredns-custom ConfigMap to append a server block:
apiVersion: v1
kind: ConfigMap
metadata:
name: coredns-custom
namespace: kube-system
data:
corp.server: |
corp.contoso.com:53 {
errors
cache 30
forward . 10.10.0.4 10.10.0.5
}
Limit: a more common approach is VNet-level custom DNS or Azure DNS Private Resolver. Nodes inherit it, and CoreDNS's default forward works as is.
Case 3: StatefulSet cluster self-discovery fails
Problem: a 3-replica etcd or Kafka-style StatefulSet gets stuck on first start. Members discover each other through pod-0.svc, but not-ready Pods have no DNS records, which creates a chicken-and-egg problem.
Approach: set publishNotReadyAddresses: true on the headless Service, and make sure the StatefulSet's serviceName matches the headless Service name.
Common errors and fixes
;; connection timed out; no servers could be reached
Cause: the CoreDNS Pods are unhealthy, the kube-dns Service has no endpoints, or a NetworkPolicy default-denies egress on port 53 (the most common cause in Module 7).
kubectl -n kube-system get pods -l k8s-app=kube-dns -o wide kubectl -n kube-system get endpointslices -l kubernetes.io/service-name=kube-dns kubectl -n shop get networkpolicy kubectl -n shop exec netshoot -- dig @10.96.0.10 kubernetes.default.svc.cluster.local +short
Fix: restore CoreDNS, or allow UDP and TCP 53 with an egress policy to the k8s-app=kube-dns Pods in kube-system.
[FATAL] plugin/loop: Loop (127.0.0.1:xxxx -> :53) detected for zone "."
Cause: the node's /etc/resolv.conf points to a local stub (such as systemd-resolved's 127.0.0.53). CoreDNS forwards to itself, forming a loop, and CoreDNS goes into CrashLoopBackOff.
Fix: make the kubelet use a resolv.conf that lists the real upstream (resolvConf: /run/systemd/resolve/resolv.conf), or forward to an explicit upstream IP in the Corefile.
nslookup resolves, but the app reports Name or service not known / getaddrinfo ENOTFOUND
Cause: nslookup and dig behave differently from libc (search, ndots, /etc/hosts, nsswitch). alpine (musl) handles search domains and TCP fallback differently from glibc. Or DNS answers larger than 512 bytes need TCP, but the policy allows only UDP 53.
kubectl -n shop exec <pod> -- getent hosts <name> kubectl -n shop exec netshoot -- dig +tcp <name>
Fix: use FQDNs, and allow both UDP and TCP 53 in the NetworkPolicy.
Accessing an ExternalName Service returns 404 / TLS: certificate is valid for api.example.com, not payments.shop.svc.cluster.local
Cause: ExternalName is just a CNAME. The client still sends the in-cluster name in the Host header and SNI (see the Caution in the official docs).
Fix: for HTTP(S), use the external domain directly, or rewrite the Host header through a Gateway or egress proxy.
1. Write the command that looks up the stable domain name of Pod 0 in the db StatefulSet, and resolves its IP.
kubectl -n shop exec netshoot -- dig +short db-0.db.shop.svc.cluster.local
2. Write a Pod spec fragment that sets ndots to 1 for a Pod while keeping cluster DNS.
spec:
dnsPolicy: ClusterFirst
dnsConfig:
options:
- {name: ndots, value: "1"}A service accesses storage.blob.core.windows.net 2,000 times per second, and CoreDNS CPU spikes. Analyze the cause and give 3 improvements.
The name has 4 dots, which is fewer than ndots 5, so each lookup first walks the 3 search domains (each with A and AAAA). That is 8 queries per lookup, 6 of which return NXDOMAIN. CoreDNS's default cache may not cache negative answers for cluster.local, which amplifies the load. Improvements: ① use FQDNs with a trailing dot, or set ndots: 2; ② reuse connections and cache resolution results in the app; ③ deploy NodeLocal DNSCache and scale CoreDNS (or enable CoreDNS autoscaling).
Verified teaching videos
Titles and channels were verified via YouTube oEmbed. No verified video specifically covering ndots was found.
Official docs
Video storyboard script
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
On screen: a close-up of the terminal showing cat /etc/resolv.conf inside a Pod, with three lines highlighted one after another.
Narration: The kubelet writes each Pod's resolv.conf. The nameserver is the ClusterIP of kube-dns, the search list contains three cluster domains, and ndots is set to five.
On screen: login.microsoftonline.com is entered, and four candidate names appear one by one. The first three get red crosses, and the last one gets a green check. The counter jumps to 8.
Narration: This name has only two dots, which is fewer than five. So the resolver first appends the three search domains, and each one also queries A and AAAA. That is eight queries in total.
On screen: a regular Service returns one VIP; a headless Service returns multiple Pod IPs; db-0 under the StatefulSet db is highlighted.
Narration: A regular Service returns a virtual IP. A headless Service returns Pod IPs directly. Each Pod in a StatefulSet also has its own stable domain name.
On screen: a small cache box at 169.254.20.10 appears on each node.
Narration: Large clusters can enable NodeLocal DNSCache, so queries are answered from the local node's cache first.
Module 4 · LoadBalancer and External Traffic
- Explain how NodePort (default range 30000–32767) relates to LoadBalancer. LB = NodePort + a cloud load balancer (created by the cloud-controller-manager).
- Compare
externalTrafficPolicy: ClusterandLocal: extra hops, SNAT, source IP preservation,healthCheckNodePort, and uneven load. - Use the Azure LB annotations commonly used on AKS (internal LB, specifying a subnet or IP, PLS), and
loadBalancerSourceRanges. - Use cloud-provider-kind in kind to get a LoadBalancer IP that is actually reachable.
What: three stacked Service types
| Type | What it allocates | Who implements it | How to access it |
|---|---|---|---|
| ClusterIP | Virtual IP | kube-proxy | In-cluster |
| NodePort | ClusterIP, plus the same port on every node (default range 30000–32767, --service-node-port-range) | kube-proxy | <any node IP>:<nodePort> |
| LoadBalancer | NodePort, plus an external load balancer IP (status.loadBalancer.ingress) | cloud-controller-manager (on AKS, cloud-provider-azure creates and updates the Azure Load Balancer rules and probes), or MetalLB, cloud-provider-kind, and similar | LB IP:port |
The LB controller watches Services of type: LoadBalancer. It calls the cloud API to create a frontend IP, a backend pool (node or Pod IPs), load balancing rules, and health probes, then writes the IP back to the Service status. allocateLoadBalancerNodePorts: false (GA v1.24) skips the NodePort when the LB reaches Pod IPs directly. loadBalancerClass (GA v1.24) selects a non-default LB implementation.
Why: externalTrafficPolicy determines the source IP and the number of hops
| Cluster (default) | Local | |
|---|---|---|
| Node that receives the traffic | Can forward to backends on any node | Forwards only to backends on this node |
| SNAT | Yes. To make return traffic follow the same path, the source IP is changed to the node IP. | No: the client source IP is preserved |
| Extra hop | Possible (node A → node B) | None |
| Node with no local backend | Still forwards | Dropped. So the LB must know which nodes have backends. kube-proxy serves an HTTP health check on healthCheckNodePort (it returns 200 if there are local endpoints, otherwise 503), and the LB uses it to remove nodes without backends from the backend pool. |
| Load balancing | Even (per endpoint) | Even per node. It becomes uneven when Pods are unevenly distributed (mitigate with topologySpreadConstraints). |
How: restricting sources and Azure annotations
spec.loadBalancerSourceRanges: ["203.0.113.0/24"]: the cloud LB or NSG, or kube-proxy rules, allow only these sources (AKS converts this to NSG rules).- AKS internal LB:
service.beta.kubernetes.io/azure-load-balancer-internal: "true". Specify a subnet:…/azure-load-balancer-internal-subnet: "apps-subnet". Specify an IP:…/azure-load-balancer-ipv4: 10.240.0.25. (Microsoft Learn recommends annotations instead ofspec.loadBalancerIP, which is going to be deprecated.) - For Private Link Service:
service.beta.kubernetes.io/azure-pls-create: "true". This requires Standard LB. If you useexternalTrafficPolicy: Local, the PLS subnet must be different from the Pod subnet. - AKS no longer supports Basic Load Balancer as of 2025-09-30. Use Standard LB across the board.
When: how to choose the entry point
| Requirement | Choose |
|---|---|
| Non-HTTP L4 services (database proxies, MQTT, UDP games) | LoadBalancer Service (or Gateway API TCPRoute/UDPRoute) |
| Multiple HTTP services sharing one IP, routed by domain or path, with TLS termination | Gateway API (Module 6), whose data plane is usually itself exposed through one LoadBalancer Service |
| Need the real client IP for auditing or rate limiting | externalTrafficPolicy: Local, or X-Forwarded-For / PROXY protocol at an L7 proxy |
| Reachable only inside the VNet | Internal LB annotation + loadBalancerSourceRanges |
Architecture diagram: control plane and data plane of a LoadBalancer
Data-flow diagram: how the source address changes under Cluster and Local
Comparison animation: externalTrafficPolicy Cluster vs Local
Choose a mode and where the traffic lands, then play to watch the hop path, the SNAT, and the source IP the backend sees.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl expose deploy web --type=LoadBalancer --port=80 | Quickly create an LB Service | Manage production with YAML |
kubectl get svc -w | Watch EXTERNAL-IP change from pending to assigned | If it stays pending, check the describe events |
kubectl patch svc X -p '{"spec":{"externalTrafficPolicy":"Local"}}' | Switch the traffic policy | Switching to Local automatically allocates healthCheckNodePort |
curl http://NODE:HCNP/healthz | Check the kube-proxy health check result | Returns JSON that includes localEndpoints |
kubectl describe svc X | Check LB events | EnsuringLoadBalancer / EnsuredLoadBalancer / SyncLoadBalancerFailed |
apiVersion: apps/v1
kind: Deployment
metadata:
name: echo
namespace: shop
spec:
replicas: 1
selector:
matchLabels: {app: echo}
template:
metadata:
labels: {app: echo}
spec:
nodeSelector:
kubernetes.io/hostname: lab-worker # pinned to lab-worker for easy comparison
containers:
- name: agnhost
image: registry.k8s.io/e2e-test-images/agnhost:2.39
args: ["netexec", "--http-port=8080"]
ports:
- {containerPort: 8080}
---
apiVersion: v1
kind: Service
metadata:
name: echo-lb
namespace: shop
spec:
type: LoadBalancer
externalTrafficPolicy: Cluster
selector: {app: echo}
ports:
- {name: http, port: 80, targetPort: 8080}
kubectl apply -f echo-lb.yaml
kubectl -n shop get svc echo-lb -w # wait for EXTERNAL-IP; press Ctrl+C to exit
LB=$(kubectl -n shop get svc echo-lb -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
NP=$(kubectl -n shop get svc echo-lb -o jsonpath='{.spec.ports[0].nodePort}')
echo LB=$LB NP=$NP
curl -s http://$LB/clientip; echo
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE echo-lb LoadBalancer 10.96.77.120 <pending> 80:31080/TCP 2s echo-lb LoadBalancer 10.96.77.120 172.18.0.6 80:31080/TCP 5s LB=172.18.0.6 NP=31080 172.18.0.3:48122
How to verify: EXTERNAL-IP is a new Envoy container on the kind network (docker ps | grep kindccm; the container name prefix depends on your setup). Common mistake: cloud-provider-kind is not running, so the IP stays pending. Production use: on AKS, this step creates Azure LB rules and a public IP, which incur charges.
apiVersion: v1
kind: Service
metadata:
name: api-internal
namespace: shop
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal: "true"
service.beta.kubernetes.io/azure-load-balancer-internal-subnet: "apps-subnet"
spec:
type: LoadBalancer
externalTrafficPolicy: Local
loadBalancerSourceRanges: ["10.20.0.0/16"]
selector: {app: api}
ports:
- {name: http, port: 80, targetPort: http}
Lab 4: Observe SNAT and source IP preservation (about 7 minutes)
172.18.0.1. No cloud costs.W2=$(docker inspect -f '{{.NetworkSettings.Networks.kind.IPAddress}}' lab-worker2)
W1=$(docker inspect -f '{{.NetworkSettings.Networks.kind.IPAddress}}' lab-worker)
curl -s http://$W2:$NP/clientip; echo # traffic enters lab-worker2 and is forwarded to the Pod on lab-worker
curl -s http://$W1:$NP/clientip; echo # traffic goes straight to the Pod's node
172.18.0.3:39012 ← lab-worker2's node IP (SNAT) 10.244.1.1:51770 ← address after SNAT on this node (in Cluster mode, external sources are masqueraded; the exact address depends on the implementation)
kubectl -n shop patch svc echo-lb -p '{"spec":{"externalTrafficPolicy":"Local"}}'
HC=$(kubectl -n shop get svc echo-lb -o jsonpath='{.spec.healthCheckNodePort}'); echo HC=$HC
curl -s -m 3 http://$W1:$NP/clientip; echo
curl -s -m 3 http://$W2:$NP/clientip || echo "no local endpoint on lab-worker2: timed out or dropped"
curl -s http://$W1:$HC/healthz; echo
curl -s -o /dev/null -w '%{http_code}\n' http://$W2:$HC/healthz
HC=32514
172.18.0.1:52340 ← the real client (host) address is preserved
no local endpoint on lab-worker2: timed out or dropped
{"service":{"namespace":"shop","name":"echo-lb"},"localEndpoints":1,…}
503curl -s http://$LB/clientip; echo
docker ps --format '{{.Names}}\t{{.Image}}' | grep -i envoy
Even with Local, what you see here is the address of cloud-provider-kind's Envoy container. It is an L4 proxy-type LB that re-establishes the connection. Azure Load Balancer is pass-through, and in Local mode the Pod can see the real public client IP. This is direct evidence that whether the source IP is preserved depends on the whole path.
kubectl -n shop patch svc echo-lb -p '{"spec":{"loadBalancerSourceRanges":["10.0.0.0/8"]}}'
curl -s -m 3 http://$LB/clientip || echo "rejected by source range (whether the LB or kube-proxy enforces this depends on the implementation)"
kubectl -n shop patch svc echo-lb --type=json -p '[{"op":"remove","path":"/spec/loadBalancerSourceRanges"}]'kubectl delete -f echo-lb.yaml. The LB container is removed along with the Service.Case 1: all the WAF logs show node IPs
Problem: a self-built Envoy or Nginx entry point on AKS. The client IPs in the app and WAF logs are all 10.240.x.x, so clients cannot be blocked by IP.
Approach: change the entry Service to externalTrafficPolicy: Local. Spread the entry Deployment across nodes with topologySpreadConstraints or a DaemonSet to avoid skewed load. The entry proxy writes the real IP into X-Forwarded-For and passes it to the backend.
Limit: when entry Pods roll on a node, the LB probes take several seconds to remove that node. Plan for this with a preStop hook and a sufficient terminationGracePeriodSeconds.
Case 2: an internal service that only the Hub VNet can reach
Problem: a reporting API should be reachable only from the office network, which connects through ExpressRoute.
Approach: internal LB annotation + dedicated subnet annotation + loadBalancerSourceRanges limited to the office network ranges. Consumers across tenants or subscriptions are exposed as a Private Link Service via azure-pls-create, and the other side creates a Private Endpoint.
Case 3: one public IP per service, costs out of control
Problem: 40 microservices each use type: LoadBalancer, giving 40 public IPs and rule sets. Security auditing is difficult.
Approach: consolidate into 1–2 Gateways (Module 6), with all HTTP services using HTTPRoute. Keep a separate LB only for services that truly need L4.
Common errors and fixes
EXTERNAL-IP keeps showing <pending>
Cause: there is no LB controller (kind is not running cloud-provider-kind, or bare metal has no MetalLB installed). On the cloud, the cause is quota, permissions (the cluster identity lacks Network Contributor), or insufficient subnet IPs. It can also happen when a loadBalancerClass is set that no controller claims.
kubectl describe svc echo-lb | sed -n '/Events/,$p'
docker ps | grep -i cloud-provider-kind; docker logs cloud-provider-kind --tail 30
kubectl get svc echo-lb -o jsonpath='{.spec.loadBalancerClass}'Warning SyncLoadBalancerFailed … Error syncing load balancer: failed to ensure load balancer: … AuthorizationFailed
Cause: the AKS cluster's managed identity lacks permissions on the custom VNet or subnet, or on the resource group of the public IPs.
az aks show -g rg-k8s-lab -n aks-lab --query identity az role assignment list --assignee <principalId> -o table
Fix: grant the cluster identity Network Contributor on the VNet that contains the subnet (or a custom role that includes subnets/join/action and subnets/read).
Some requests time out after changing to externalTrafficPolicy: Local
Cause: the LB health probe does not use healthCheckNodePort (a custom probe annotation overrides it, or an NSG blocks the probe port). Traffic is sent to nodes with no local Pods and dropped.
kubectl get svc X -o jsonpath='{.spec.healthCheckNodePort}'
for n in $(kubectl get nodes -o jsonpath='{.items[*].status.addresses[0].address}'); do echo -n "$n "; curl -s -o /dev/null -w '%{http_code}\n' http://$n:<HCNP>/healthz; done
Fix: confirm that the cloud LB probe points to healthCheckNodePort, and allow the probe source (Azure: 168.63.129.16).
The Service "x" is invalid: spec.ports[0].nodePort: Invalid value: 8080: provided port is not in the valid range. The range of valid ports is 30000-32767
Cause: the manually specified nodePort is outside --service-node-port-range, or it is already in use (“provided port is already allocated”).
Fix: leave nodePort unset so the system assigns one. If you need a fixed port, pick one from the static band (default 30000–30085) to lower the chance of conflicts with dynamic allocation.
1. Switch the Service web-lb to the mode that preserves the source IP, and retrieve the health check port that kube-proxy allocated for it.
kubectl -n shop patch svc web-lb -p '{"spec":{"externalTrafficPolicy":"Local"}}'
kubectl -n shop get svc web-lb -o jsonpath='{.spec.healthCheckNodePort}'2. Write the annotations for an AKS internal LB with a fixed IP of 10.240.0.25.
metadata:
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal: "true"
service.beta.kubernetes.io/azure-load-balancer-ipv4: 10.240.0.25After the entry Service changed to Local, the source IP was preserved. But monitoring shows that on one of the 3 nodes, the entry Pod CPU is 3 times higher than on the others. Why? What should you do?
In Local mode, the LB splits traffic evenly across nodes, and each node then hands its share to its local Pods. If one node has 3 entry Pods while each other node has 1, the load per Pod is uneven. Or one node has 2 Pods while another has 0 and is removed, so a single node takes more load. Approach: change the entry to a DaemonSet, or use topologySpreadConstraints (maxSkew 1, by hostname) to keep the Pod count per node consistent. Alternatively, consider an LB that supports direct Pod IPs (such as Application Gateway for Containers on AKS).
Verified teaching videos
Titles and channels were verified via YouTube oEmbed. No verified video specifically covering externalTrafficPolicy was found.
Official docs
- Create an External Load Balancer (source IP preservation)
- Using Source IP
- AKS internal load balancer (Microsoft Learn, 2026-07-31)
- cloud-provider-azure LoadBalancer annotations
- cloud-provider-kind
Video storyboard script
This courseware cannot generate video or MP3 directly, so a storyboard and narration script are provided instead.
On screen: three nested boxes, ClusterIP ⊂ NodePort ⊂ LoadBalancer.
Narration: A LoadBalancer is a NodePort with a cloud load balancer added on top, and a NodePort in turn includes a ClusterIP.
On screen: a CCM robot reads the Service, calls the Azure API, and the frontend IP is written back to the Service.
Narration: The cloud controller manager watches Services of type LoadBalancer. It creates the frontend IP, backend pool, and probes in the cloud, then writes the IP back to the Service status.
On screen: split screen. Left: the packet goes to node C, its source address is rewritten, and it hops to node A. Right: node C's probe shows 503 and it is removed from the backend pool, so the packet goes straight to node A.
Narration: Cluster mode may add a hop and translate the source address. Local mode sends traffic only to local Pods and preserves the client IP. It uses the health check port to remove nodes that have no Pods.
Module 5 · Ingress and the ingress-nginx Retirement
- Read and write Ingress: IngressClass, rules, pathType (Prefix, Exact, ImplementationSpecific), TLS, and defaultBackend.
- State the current situation accurately: the Ingress API is still GA and has no removal plan, but it is frozen and no longer being developed. The ingress-nginx controller was archived on 2026-03-24. Its final version is v1.15.1, and it no longer receives security patches.
- Use ingress2gateway 1.0 to convert ingress-nginx configuration to the Gateway API, and list the annotations that need manual handling.
- Understand the current status of the AKS Application Routing add-on and its migration options.
What: Ingress = rules (API object) + controller (implementation)
Ingress is the object in networking.k8s.io/v1 that describes “HTTP(S) hostname/path → Service”. It does nothing by itself. An Ingress controller (nginx, Traefik, HAProxy, Contour, Kong, Istio, Cilium, cloud-provider controllers, and so on) watches it and configures the actual proxy. An IngressClass specifies which controller handles an Ingress (spec.ingressClassName), and it can be marked as the default with ingressclass.kubernetes.io/is-default-class: "true".
| pathType | Match semantics | /api rule vs request |
|---|---|---|
| Exact | Exact match, case-sensitive | /api ✓; /api/ ✗; /api/v1 ✗ |
| Prefix | Prefix match by path /-separated elements | /api ✓; /api/ ✓; /api/v1 ✓; /apis ✗ |
| ImplementationSpecific | Decided by the controller (in ingress-nginx it can be a regex) | Not portable. This is the biggest pitfall when migrating. |
When several rules match, the longest path wins. For equal lengths, Exact takes precedence over Prefix.
Why: why migrate
- ingress-nginx retirement (announced by the Kubernetes SIG Network and Security Response Committee in 2025-11): the repository was archived on 2026-03-24. The final version is v1.15.1 (2026-03-19), and it receives no security patches of any kind. Continuing to run it means the most exposed component at the edge no longer gets CVE fixes.
- The Ingress API is frozen: kubernetes.io states “Ingress API is generally available… no plans to remove Ingress”, but it is “no longer being developed,” and the project recommends Gateway. Feature gaps (header matching, traffic splitting, cross-namespace routing, L4) have long been filled by vendor-specific annotations, which cannot be ported.
- Multi-tenant security: annotations and snippets let anyone who can create an Ingress affect the global configuration of a shared proxy. This has caused several CVEs in the past.
How: the migration path
- Inventory: list all Ingresses, IngressClasses, and the annotations in use (
kubectl get ingress -A -o yaml | grep -o 'nginx.ingress.kubernetes.io/[a-z-]*' | sort | uniq -c). - Choose an implementation: a Gateway API implementation (Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, Kong, Traefik, cloud-provider implementations, and others; see the implementations list at gateway-api.sigs.k8s.io), or another actively maintained Ingress controller as a transition step.
- Convert:
ingress2gateway print --providers=ingress-nginx. Version 1.0 was released on 2026-03-20 and supports 30+ ingress-nginx annotations. The providers currently supported include apisix, cilium, ingress-nginx, istio, gce, kong, nginx, openapi, and traefik. - Run in parallel: the new Gateway gets a new IP, which you verify with a test domain. Switch DNS one domain at a time (lower the TTL first), and decommission the old controller only after you have observed the result.
- Manual follow-up: annotations the converter can't express (rate limiting, authentication, Lua/snippets, body size) must be handled with the implementation's extension policies (such as Envoy Gateway's BackendTrafficPolicy and SecurityPolicy) or moved to the application layer.
When: what AKS users should do (Microsoft Learn, updated 2026-10)
- The managed NGINX in the AKS Application Routing add-on is based on the upstream ingress-nginx. Microsoft's official support for its critical security patches runs through November 2026, so migrate before then.
- For the long term, AKS uses Gateway API as the standard. Migrate to the Gateway API implementation in Application Routing (GatewayClass
approuting-istio; it deploys an Istio control plane that manages only the Gateway infrastructure and doesn't inject sidecars. Enable withaz aks update … --enable-gateway-api --enable-app-routing-istio; the Managed Gateway API CRDs must be enabled), or Application Gateway for Containers (supports both the Ingress API and the Gateway API), or Gateway API through the Istio add-on. - Starting with AKS 1.36, newly created AKS Automatic clusters enable Gateway API through Application Routing by default. Limitations: this implementation doesn't support request header and body size limits, Lua, rate limiting, and similar features (consider the Istio add-on with EnvoyFilter).
kubernetes/ingress-nginx. Whether to use it depends on its official support policy. ③ “ingress2gateway is a one-click, lossless migration”: it's a starting point. You must review the output and test it, especially regex paths, rewrite-target, and snippets.| Comparison | Ingress | Gateway API |
|---|---|---|
| API status | GA, frozen | GA (Standard channel), still evolving (v1.6) |
| Protocols | HTTP/HTTPS | HTTP, HTTPS, gRPC, TLS passthrough, TCP, UDP |
| Header/query matching, weights | Implementation-specific annotations | Standard fields |
| Role separation | One object mixes infrastructure and routing | GatewayClass / Gateway / Route belong to different roles |
| Cross-namespace | Not supported (or implementation-specific extensions) | allowedRoutes + ReferenceGrant |
Architecture diagram: the Ingress controller pattern (and the retirement's impact)
Flow diagram: five migration steps
Interactive demo: pathType matcher
Below is an Ingress with three rules. Enter a request path to see whether each rule matches and which one wins (the longest path takes precedence; for equal lengths, Exact wins).
| # | path | pathType | backend | Match? |
|---|
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl get ingressclass | List the Ingress controller classes in the cluster | Check the default class annotation |
kubectl get ingress -A | Inventory Ingresses | -o yaml to export annotations |
kubectl create ingress … --rule="host/path*=svc:port,tls=secret" | Create an Ingress imperatively | A trailing * means Prefix |
ingress2gateway print --providers=ingress-nginx -A | Read all Ingresses in the cluster across namespaces and output Gateway API YAML | --namespace, --input-file (repeatable) |
kubectl get pods -A -l app.kubernetes.io/name=ingress-nginx | Find ingress-nginx that is still running | The image tag confirms the version |
go install github.com/kubernetes-sigs/ingress2gateway@v1.0.0 # or brew install ingress2gateway, or download the binary from Releases ingress2gateway version
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: shop
namespace: shop
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/canary: "false"
spec:
ingressClassName: nginx
tls:
- hosts: [shop.example.test]
secretName: shop-tls
rules:
- host: shop.example.test
http:
paths:
- path: /api
pathType: Prefix
backend:
service: {name: api, port: {number: 9898}}
- path: /
pathType: Prefix
backend:
service: {name: web, port: {number: 80}}
ingress2gateway print --providers=ingress-nginx --input-file=shop-ingress.yaml > shop-gw-converted.yaml cat shop-gw-converted.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: nginx
namespace: shop
spec:
gatewayClassName: nginx
listeners:
- name: shop-example-test-http
hostname: shop.example.test
port: 80
protocol: HTTP
- name: shop-example-test-https
hostname: shop.example.test
port: 443
protocol: HTTPS
tls:
certificateRefs:
- {group: "", kind: Secret, name: shop-tls}
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop-shop-example-test
namespace: shop
spec:
hostnames: [shop.example.test]
parentRefs:
- name: nginx
rules:
- matches:
- path: {type: PathPrefix, value: /api}
backendRefs:
- {name: api, port: 9898}
- matches:
- path: {type: PathPrefix, value: /}
backendRefs:
- {name: web, port: 80}
…(ssl-redirect generates an HTTP rule with a RequestRedirect filter)
How to verify: compare each rule in the original Ingress with its matching HTTPRoute rule in the output, and check the conversion log for “unsupported annotation” warnings. Common mistake: applying the output as is. gatewayClassName: nginx doesn't exist in the cluster, so change it to your implementation (eg in this lesson). Production use: generate a migration draft and put it through Git review.
Lab 5: Migrate existing Ingress to Envoy Gateway (about 6 min)
eg.openssl req -x509 -nodes -newkey rsa:2048 -days 30 \ -keyout shop.key -out shop.crt -subj "/CN=shop.example.test" \ -addext "subjectAltName=DNS:shop.example.test" kubectl -n shop create secret tls shop-tls --cert=shop.crt --key=shop.key
ingress2gateway print --providers=ingress-nginx --input-file=shop-ingress.yaml > shop-gw-converted.yaml grep -nE 'kind:|gatewayClassName|value:' shop-gw-converted.yaml
eg and rename the Gateway to shop-migrated (update the Route's parentRefs to match).
GWNAME=$(awk '/kind: Gateway$/{f=1} f&&/name:/{print $2; exit}' shop-gw-converted.yaml); echo $GWNAME
sed -e "s/gatewayClassName: .*/gatewayClassName: eg/" \
-e "s/name: $GWNAME\$/name: shop-migrated/" shop-gw-converted.yaml > shop-gw-eg.yaml
kubectl apply -f shop-gw-eg.yaml
kubectl -n shop get gateway,httproute
NAME CLASS ADDRESS PROGRAMMED AGE gateway.gateway.networking.k8s.io/shop-migrated eg 172.18.0.7 True 20s NAME HOSTNAMES AGE httproute.gateway.networking.k8s.io/shop-shop-example-test ["shop.example.test"] 20s
GW=$(kubectl -n shop get gateway shop-migrated -o jsonpath='{.status.addresses[0].value}')
curl -s -H 'Host: shop.example.test' http://$GW/ -o /dev/null -w '%{http_code} %{redirect_url}\n'
curl -sk --resolve shop.example.test:443:$GW https://shop.example.test/
curl -sk --resolve shop.example.test:443:$GW https://shop.example.test/api/info
curl -sk --resolve shop.example.test:443:$GW https://shop.example.test/api/version -o /dev/null -w '%{http_code}\n'
301 https://shop.example.test/
shop web OK from web-6d8f9c7b4-l5kcz
{ "hostname": "api-v1-…", "version": "6.17.0", "message": "shop api v1", … }
404
Paths are forwarded to podinfo unchanged. /api/info returns 200 because it's an endpoint built into podinfo, and /api/version returns 404 because it doesn't exist in podinfo. The original Ingress has no rewrite either, so the behavior matches. Comparing behavior rule by rule like this is the core of migration verification. Module 6 uses URLRewrite to strip the prefix.
kubectl delete -f shop-gw-eg.yaml (keep the shop-tls Secret; Module 6 continues to use it).Case 1: migrating 200 Ingresses with 47 annotation types
Problem: the platform team hosts ingress-nginx for 30 business teams. After the retirement notice, they must migrate before the patch deadline.
Approach: ① a script counts annotation usage and groups them into three categories: “converts automatically,” “needs an implementation extension,” and “needs application changes.” ② ingress2gateway generates drafts in bulk, and a GitOps PR has each team confirm them. ③ Each team gets its own Gateway listener or HTTPRoute, and the infrastructure team manages only the Gateway. ④ Cut over the test domain first, then switch DNS domain by domain during business off-peak hours.
Limitations: configuration-snippet, server-snippet, and Lua can't be converted automatically and must be redesigned.
Case 2: AKS Application Routing (managed NGINX) migration
Problem: the AKS cluster uses the webapprouting.kubernetes.azure.com IngressClass.
Approach: following Microsoft Learn, enable Managed Gateway API and --enable-app-routing-istio, create a Gateway with gatewayClassName: approuting-istio, convert the Routes, verify in parallel, then switch DNS. If you need body size limits, rate limiting, or similar features, evaluate the Istio add-on or Application Gateway for Containers.
Limitations: can't be enabled together with the Istio service mesh add-on, and not supported with self-managed Gateway API CRDs (you must use the AKS-managed CRDs).
Case 3: risk mitigation when migration isn't possible yet
If you really must keep running ingress-nginx during the transition: disable snippet annotations, restrict who can create Ingresses (RBAC), turn off external exposure of the admission webhook, put a WAF in front as a safety net, and set a clear decommission date. These are only mitigations and don't replace migration.
Common errors and fixes
Ingress created successfully, but ADDRESS stays empty
Cause: no controller is processing it. The ingressClassName is misspelled, the cluster has no matching controller, or there is no default IngressClass.
kubectl get ingressclass
kubectl -n shop get ingress shop -o jsonpath='{.spec.ingressClassName}'; echo
kubectl -n shop describe ingress shop/apis returns the web page instead of 404 (or the /api rule doesn't match /apis)
Cause: Prefix matches by path element, so /api doesn't match /apis, and the request falls through to the / rule. This is the specified behavior.
Fix: if needed, add a separate rule for /apis. Don't rely on string-prefix behavior.
404 after migration: the original Ingress uses nginx.ingress.kubernetes.io/rewrite-target: /$2 with regex paths
Cause: regex paths (ImplementationSpecific) and rewrite-target are ingress-nginx-specific behaviors.
Fix: in the HTTPRoute, use PathPrefix + the URLRewrite filter (ReplacePrefixMatch), see Module 6. For regex patterns you can't express this way, use multiple explicit rules instead.
admission webhook "validate.nginx.ingress.kubernetes.io" denied the request / failed calling webhook
Cause: the old controller was deleted, but its ValidatingWebhookConfiguration is still there, so every Ingress change calls a service that no longer exists.
kubectl get validatingwebhookconfiguration | grep -i nginx kubectl delete validatingwebhookconfiguration ingress-nginx-admission
1. Count the ingress-nginx annotations used by all Ingresses in the cluster, and how many times each one is used.
kubectl get ingress -A -o yaml | grep -o 'nginx.ingress.kubernetes.io/[a-z0-9-]*' | sort | uniq -c | sort -rn
2. Use ingress2gateway to convert the Ingresses in the shop namespace from the cluster, and save the result.
ingress2gateway print --providers=ingress-nginx --namespace=shop > shop-gw.yaml
Your boss asks: “Ingress is deprecated. Should we delete all our Ingress YAML?” How do you answer, and what plan do you propose?
Correct the facts: the Ingress API is still GA with no removal plan, but it is frozen. What's retired is the ingress-nginx controller (archived 2026-03-24, no security patches). The risk is continuing to run an unpatched entry-point component, not the YAML itself. Plan: inventory the controllers and annotations → choose a Gateway API implementation (or a still-maintained Ingress controller as a transition step) → generate drafts with ingress2gateway → run in parallel and switch domain by domain → decommission ingress-nginx and leftover webhooks. AKS users: note that managed NGINX support runs through 2026-11.
Verified teaching videos
Titles and channels were verified via YouTube oEmbed (2026-11-15).
Official docs and announcements
- Ingress · Ingress Controllers (includes the “Ingress API has been frozen” note)
- Ingress NGINX Retirement announcement
- ingress2gateway
- AKS Application Routing (managed NGINX, 2026-10-26) · Application Routing Gateway API
Video storyboard
This lesson can't generate video or MP3 directly, so a storyboard and narration script are provided instead.
On screen: two signs, “Ingress API: GA, still here” (green) and “ingress-nginx controller: archived 2026-03-24” (red).
Narration: first, let's clear up one fact. What's retired is the ingress-nginx controller, not the Ingress API.
On screen: the paths /api, /api/, and /apis hit the Prefix rule in turn. The first two pass, and the last one is rejected.
Narration: Prefix matches by path element. The path /api does not match /apis.
On screen: a five-step migration timeline, with ingress2gateway turning one Ingress card into two cards, a Gateway and an HTTPRoute.
Narration: inventory, choose, convert, verify in parallel, decommission the old controller. The conversion tool is only a starting point, and implementation-specific annotations must be handled by hand.
Module 6 · Gateway API v1.6
- Use the role model to explain how GatewayClass (infrastructure provider), Gateway (cluster operations), and HTTPRoute (application development) divide the work, and where the RBAC boundaries are.
- Configure listeners, hostname, and allowedRoutes, and understand how a Route attaches to a Gateway (parentRefs/sectionName).
- Use HTTPRoute matches (path/header/query/method), filters (RequestHeaderModifier, RequestRedirect, URLRewrite, RequestMirror), and backendRefs weights.
- Understand ReferenceGrant, GRPCRoute, TCPRoute/UDPRoute, TLS termination, and status conditions (Accepted / Programmed / ResolvedRefs).
What: resources and roles
| Resource | Scope | Managed by | Description |
|---|---|---|---|
| GatewayClass | Cluster-level | Infrastructure provider (cloud vendor / platform team) | Declares which controller implements a class of Gateways (controllerName), similar to a StorageClass |
| Gateway | Namespace | Cluster operations / platform team | A specific traffic entry point: listeners (port, protocol, hostname, TLS) plus which Routes are allowed to attach |
| HTTPRoute / GRPCRoute | Namespace | Application developer | L7 routing rules: match → filter → backend |
| TLSRoute / TCPRoute / UDPRoute | Namespace | Application developer | L4/passthrough routes (TCPRoute/UDPRoute move to the Standard channel in v1.6) |
| ReferenceGrant | Namespace (referenced side) | Owner of the referenced resource | Explicitly grants “objects in another namespace may reference my namespace's Services/Secrets” |
Channels: the Standard channel includes only GA/stable resources and fields, with backward-compatibility guarantees. The Experimental channel includes experimental fields and resources (such as early versions of BackendTLSPolicy). This lesson installs only Standard.
Why: key improvements over Ingress
- Role separation: developers can change routes but not certificates or ports. The platform team uses
allowedRoutesto control which namespaces can attach. - Standard expressiveness: Header/Query/Method matching, weights, redirects, rewrites, mirroring, and header modification are all standard fields, portable across implementations (covered by conformance tests).
- Multiple protocols: HTTP, gRPC, TLS passthrough, TCP, UDP.
- Observable status: every object has standardized conditions, so you can see the cause of a misconfiguration directly in
kubectl describe.
How: the flow of a request
- The request reaches the Gateway's data plane (Envoy Gateway creates a set of Envoy Deployments plus a LoadBalancer Service for each Gateway).
- Select the listener by port, protocol, SNI, or Host. Only consider the Accepted Routes attached to that listener.
- Among the rules of those Routes, find all matches (conditions within one match are AND, and the matches list is OR), then pick one by priority: Exact path > longest prefix > has method > more header matches > more query matches. If still tied, pick the earliest-created Route, then sort alphabetically by “namespace/name”.
- Run the filters (such as rewriting the prefix, adding headers, mirroring), then pick a backend Service in proportion to the
weightinbackendRefs. The data plane load-balances directly to the Pod IPs in the EndpointSlice, usually bypassing kube-proxy.
Quick field reference
| Field | Values / notes |
|---|---|
listeners[].allowedRoutes.namespaces.from | Same (default) / All / Selector (with namespace labels) |
matches[].path.type | Exact, PathPrefix, RegularExpression (implementation-specific) |
matches[].headers / queryParams | type: Exact (core) / RegularExpression (implementation-specific) |
filters[].type | RequestHeaderModifier, ResponseHeaderModifier, RequestRedirect, URLRewrite, RequestMirror, ExtensionRef |
backendRefs[].weight | Relative weights; 90/10 means 90% and 10%; weight 0 means no traffic is sent |
parentRefs[].sectionName | Attach only to a specific listener (for example, only to https) |
When: which Route to use
| Requirement | Route |
|---|---|
| Web/REST, routed by host/path/header, TLS terminated at the Gateway | HTTPRoute (listener protocol HTTPS + certificateRefs) |
| gRPC routing by service/method | GRPCRoute |
| TLS not decrypted at the Gateway (end-to-end encryption, forwarded by SNI) | TLSRoute (listener protocol TLS, mode Passthrough) |
| Non-HTTP protocols such as databases, MQTT, DNS | TCPRoute / UDPRoute |
status.parents[].conditions. Accepted=False (such as NotAllowedByListeners) or ResolvedRefs=False (such as BackendNotFound or RefNotPermitted) both mean it isn't in effect. ② “A 90/10 weight is an exact request ratio.” It's a statistical ratio, so small samples will deviate. ③ “Gateway API must replace all Ingresses.” The two can coexist, and you can migrate service by service. ④ “A Route can reference any Service in another namespace.” A cross-namespace backendRef needs a ReferenceGrant created in the other namespace.Architecture diagram: role model and object relationships
Data flow diagram: how a request is matched
Interactive simulator: which rule does the request hit?
Below are the rules attached to shop-gw in this lesson's lab. R1–R4 match the routes.yaml on the Lab tab exactly, and R5 is an extra rule added to demonstrate Query matching (not created in the lab). Enter a path, Header, and Query, then click “Send.” The simulator picks the matching rule using the Gateway API spec's priority and samples a backend by weight.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl get gatewayclass,gateway,httproute -A | Overview | The PROGRAMMED and ADDRESS columns of the Gateway |
kubectl describe httproute NAME | Check the Route's parent status | Look at the reasons for Accepted / ResolvedRefs |
kubectl wait --for=condition=Programmed gateway/NAME | Wait for the gateway to be ready (for scripts/CI) | --timeout=2m |
kubectl get gateway NAME -o jsonpath='{.status.addresses[0].value}' | Get the gateway address | — |
kubectl -n envoy-gateway-system get deploy,svc | The data plane created by Envoy Gateway | Named like envoy-shop-shop-gw-xxxx |
kubectl api-resources | grep gateway.networking.k8s.io | Confirm the installed resources and served versions | Use this to confirm the TCPRoute/UDPRoute versions |
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: shop-gw
namespace: shop
spec:
gatewayClassName: eg
listeners:
- name: http
protocol: HTTP
port: 80
hostname: shop.example.test
allowedRoutes:
namespaces:
from: Same
- name: https
protocol: HTTPS
port: 443
hostname: shop.example.test
tls:
mode: Terminate
certificateRefs:
- kind: Secret
name: shop-tls # self-signed certificate created in the Module 5 lab
allowedRoutes:
namespaces:
from: Same
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop-web
namespace: shop
spec:
parentRefs:
- name: shop-gw
hostnames: ["shop.example.test"]
rules:
- matches:
- path: {type: PathPrefix, value: /old}
filters:
- type: RequestRedirect
requestRedirect:
path: {type: ReplacePrefixMatch, replacePrefixMatch: /}
statusCode: 301
- matches:
- path: {type: PathPrefix, value: /}
backendRefs:
- {name: web, port: 80}
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: shop-api
namespace: shop
spec:
parentRefs:
- name: shop-gw
hostnames: ["shop.example.test"]
rules:
# Rule A: all requests with x-canary: true go to v2 (internal testers)
- matches:
- path: {type: PathPrefix, value: /api}
headers:
- {type: Exact, name: x-canary, value: "true"}
filters:
- type: URLRewrite
urlRewrite:
path: {type: ReplacePrefixMatch, replacePrefixMatch: /}
backendRefs:
- {name: api-v2, port: 9898}
# Rule B: remaining /api requests go through a 90/10 canary, with the /api prefix stripped and a request header added
- matches:
- path: {type: PathPrefix, value: /api}
filters:
- type: URLRewrite
urlRewrite:
path: {type: ReplacePrefixMatch, replacePrefixMatch: /}
- type: RequestHeaderModifier
requestHeaderModifier:
add:
- {name: x-shop-route, value: api-canary}
backendRefs:
- {name: api-v1, port: 9898, weight: 90}
- {name: api-v2, port: 9898, weight: 10}
kubectl apply -f gateway.yaml -f routes.yaml
kubectl -n shop wait --for=condition=Programmed gateway/shop-gw --timeout=2m
kubectl -n shop get gateway shop-gw
kubectl -n shop get httproute shop-api -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
gateway.gateway.networking.k8s.io/shop-gw condition met NAME CLASS ADDRESS PROGRAMMED AGE shop-gw eg 172.18.0.8 True 35s Accepted=True (Accepted) ResolvedRefs=True (ResolvedRefs)
How to verify: the Gateway shows Programmed=True and has an address, and every Route shows Accepted=True and ResolvedRefs=True for each parent. Common mistake: the certificate Secret doesn't exist, so the https listener shows ResolvedRefs=False (InvalidCertificateRef). Production use: use kubectl wait in CI as a release gate.
# HTTP→HTTPS redirect: attach only to the http listener
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: https-redirect, namespace: shop}
spec:
parentRefs: [{name: shop-gw, sectionName: http}]
hostnames: ["shop.example.test"]
rules:
- filters:
- type: RequestRedirect
requestRedirect: {scheme: https, statusCode: 301}
---
# Traffic mirroring: copy each request to api-v2 (the response is discarded), for shadow testing
# filters:
# - type: RequestMirror
# requestMirror:
# backendRef: {name: api-v2, port: 9898}
---
# Cross-namespace reference: allow team-b's HTTPRoute to reference Services in shop
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata: {name: allow-team-b-routes, namespace: shop}
spec:
from:
- {group: gateway.networking.k8s.io, kind: HTTPRoute, namespace: team-b}
to:
- {group: "", kind: Service}
---
# GRPCRoute: route by gRPC service/method
apiVersion: gateway.networking.k8s.io/v1
kind: GRPCRoute
metadata: {name: pricing, namespace: shop}
spec:
parentRefs: [{name: shop-gw, sectionName: https}]
hostnames: ["grpc.shop.example.test"]
rules:
- matches:
- method: {service: pricing.v1.Pricing, method: Quote}
backendRefs: [{name: pricing, port: 50051}]
The apiVersion of ReferenceGrant in the Standard channel is v1beta1 (check with kubectl api-resources | grep referencegrants). TCPRoute/UDPRoute move to Standard in v1.6, with listener protocol: TCP/UDP, and the Route has only backendRefs. Before writing the apiVersion, confirm the served version with kubectl explain tcproute | head -5.
Lab 6: Gateway + path routing + canary + header routing (about 10 min)
shop-gw in the shop namespace. It implements /api → podinfo (prefix stripped), / → nginx, a 90/10 canary, and sends x-canary: true requests to v2. Prerequisites: GatewayClass eg is Accepted; the Secret shop-tls exists (from the Module 5 lab); cloud-provider-kind is running.kubectl apply -f gateway.yaml -f routes.yaml
kubectl -n shop wait --for=condition=Programmed gateway/shop-gw --timeout=2m
GW=$(kubectl -n shop get gateway shop-gw -o jsonpath='{.status.addresses[0].value}'); echo GW=$GW
kubectl -n envoy-gateway-system get deploy,svc -l gateway.envoyproxy.io/owning-gateway-name=shop-gwH='Host: shop.example.test'
curl -s -H "$H" http://$GW/
curl -s -H "$H" http://$GW/api/version
curl -s -H "$H" -o /dev/null -w '%{http_code} -> %{redirect_url}\n' http://$GW/old/home
curl -s -H "$H" http://$GW/api/headers | grep -i x-shop-route
shop web OK from web-6d8f9c7b4-x2v9q
{ "commit": "…", "version": "6.17.0" }
301 -> http://shop.example.test/home
"X-Shop-Route": [ "api-canary" ],
/api/version is rewritten by URLRewrite to /version before being sent to podinfo. podinfo's /headers echoes the request headers, which shows that RequestHeaderModifier is working.
for i in $(seq 1 200); do curl -s -H "$H" http://$GW/api/ | grep -o '"message": "[^"]*"'; done | sort | uniq -c
181 "message": "shop api v1"
19 "message": "shop api v2 (canary)"for i in $(seq 1 10); do curl -s -H "$H" -H 'x-canary: true' http://$GW/api/ | grep -o '"message": "[^"]*"'; done | sort | uniq -c
10 "message": "shop api v2 (canary)"
Rules A and B both match the /api prefix, but A has one more header match, so it has higher priority.
kubectl -n shop patch httproute shop-api --type=json -p '[
{"op":"replace","path":"/spec/rules/1/backendRefs/0/weight","value":50},
{"op":"replace","path":"/spec/rules/1/backendRefs/1/weight","value":50}]'
for i in $(seq 1 100); do curl -s -H "$H" http://$GW/api/ | grep -o 'v[12]'; done | sort | uniq -c
# Rollback: set the weights back to 90/10 (or 100/0); takes effect within secondscurl -sk --resolve shop.example.test:443:$GW https://shop.example.test/api/version echo | openssl s_client -connect $GW:443 -servername shop.example.test 2>/dev/null | openssl x509 -noout -subject
{ "commit": "…", "version": "6.17.0" }
subject=CN = shop.example.testkubectl -n shop patch httproute shop-web --type=json -p '[{"op":"replace","path":"/spec/rules/1/backendRefs/0/name","value":"web-typo"}]'
kubectl -n shop get httproute shop-web -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
curl -s -o /dev/null -w '%{http_code}\n' -H "$H" http://$GW/
kubectl -n shop patch httproute shop-web --type=json -p '[{"op":"replace","path":"/spec/rules/1/backendRefs/0/name","value":"web"}]'
Accepted=True (Accepted) ResolvedRefs=False (BackendNotFound) 500
kubectl delete -f routes.yaml -f gateway.yaml.Case 1: multiple teams sharing one Gateway
Problem: 20 teams each want their own entry point, but the public IP and certificates are managed centrally by the platform team.
Approach: the platform team creates a Gateway in the infra namespace, with listeners using allowedRoutes.namespaces.from: Selector (selecting namespaces labeled gateway-access: shared). Each team writes an HTTPRoute in its own namespace, with parentRefs pointing to infra/shared-gw. RBAC: developers only have write permission on HTTPRoute, with no permission on Gateways or Secrets.
listeners:
- name: https
protocol: HTTPS
port: 443
hostname: "*.apps.contoso.com"
tls: {certificateRefs: [{name: wildcard-apps}]}
allowedRoutes:
namespaces:
from: Selector
selector:
matchLabels: {gateway-access: shared}
Limitation: when hostnames conflict, the spec's conflict resolution rules apply (the earlier-created one wins). Platform-level naming conventions or admission policies are needed to prevent takeover.
Case 2: automated canary with Flagger/Argo Rollouts
Problem: manually patching weights is error-prone.
Approach: progressive delivery tools support Gateway API. They automatically advance HTTPRoute weights from 5 → 25 → 50 → 100 based on Prometheus metrics (error rate, latency), and roll back automatically on failure. The 90/10 lab in this lesson is the primitive behind these tools.
Case 3: choosing a Gateway implementation on AKS
AKS managed options: Application Routing Gateway API (approuting-istio), the Istio add-on Gateway API, and Application Gateway for Containers. You can also self-host Envoy Gateway, Cilium, and others. Factors: whether you need managed upgrades, WAF, L7 extension policies (rate limiting, authentication), and whether it coexists with a mesh. AKS managed implementations require the AKS Managed Gateway API CRDs.
Common errors and fixes
Gateway PROGRAMMED False / ADDRESS empty (reason: AddressNotAssigned)
Cause: the data plane's LoadBalancer Service can't get an IP (cloud-provider-kind isn't running in kind), the GatewayClass wasn't Accepted, or the controller Pod is unhealthy.
kubectl get gatewayclass eg kubectl -n shop describe gateway shop-gw | sed -n '/Conditions/,/Events/p' kubectl -n envoy-gateway-system get svc kubectl -n envoy-gateway-system logs deploy/envoy-gateway --tail=50
HTTPRoute status: Accepted=False, reason: NotAllowedByListeners
Cause: the Route's namespace isn't allowed by the listener's allowedRoutes (default Same), or the Route's hostnames don't intersect the listener hostname (the reason may be NoMatchingListenerHostname), or sectionName is wrong.
kubectl -n team-b describe httproute X | sed -n '/Parents/,$p'
kubectl -n shop get gateway shop-gw -o jsonpath='{.spec.listeners[*].allowedRoutes}'
Fix: adjust allowedRoutes (Selector/All) or hostnames/sectionName.
HTTPRoute status: ResolvedRefs=False, reason: RefNotPermitted
Cause: a backendRef points to a Service in another namespace, but the target namespace has no matching ReferenceGrant.
Fix: create a ReferenceGrant in the referenced namespace (from: HTTPRoute@source namespace, to: Service).
curl returns 404 route_not_found (Envoy)
Cause: the request doesn't match any rule. The Host header doesn't match hostnames (accessing by IP directly when the listener has a hostname set), the path case differs, or the header value isn't an exact match.
curl -v -H 'Host: shop.example.test' http://$GW/api/ 2>&1 | grep -E '^< HTTP|^> Host'
1. Write the command that outputs, for each parent of HTTPRoute shop-api, all condition types, statuses, and reasons.
kubectl -n shop get httproute shop-api -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'2. Change the weights of the second rule in shop-api to v1:0 and v2:100 (full cutover).
kubectl -n shop patch httproute shop-api --type=json -p '[
{"op":"replace","path":"/spec/rules/1/backendRefs/0/weight","value":0},
{"op":"replace","path":"/spec/rules/1/backendRefs/1/weight","value":100}]'A team-b HTTPRoute, created in its own namespace, needs to attach to shop-gw in the shop namespace and forward /reports to team-b's own Service. What objects and changes are needed? Is a ReferenceGrant required?
① On the platform side, change shop-gw's listener allowedRoutes to Selector (or All) to allow the team-b namespace to attach. ② team-b's HTTPRoute uses parentRefs: [{name: shop-gw, namespace: shop}], with hostnames that intersect the listener. ③ The backend Service and the Route are both in team-b, so a ReferenceGrant is not needed. A ReferenceGrant is required only when a Route references a Service or Secret in another namespace (or when a Gateway references a certificate Secret in another namespace). Attaching to someone else's Gateway is controlled by allowedRoutes.
Verified teaching videos
Titles and channels were verified via YouTube oEmbed. The videos were recorded before v1.6, so for newer changes such as TCPRoute/UDPRoute moving to Standard, follow this lesson and the official docs.
Official docs
- Gateway API website (includes the API reference, implementation list, and conformance reports)
- Gateway API v1.6 release blog
- Envoy Gateway docs
- kubernetes.io: Gateway API
Video storyboard
This lesson can't generate video or MP3 directly, so a storyboard and narration script are provided instead.
On screen: three floors. The top floor is “Infrastructure provider: GatewayClass,” the middle is “Cluster operations: Gateway,” and the bottom is “Developer: HTTPRoute,” with one figure on each floor.
Narration: Gateway API splits objects by role. The provider defines the gateway class, operations creates the gateway and its listeners, and developers write only routes.
On screen: a request card “/api/info + x-canary:true” comes in, two rules light up, the rule with the header wins, and the card is sent to v2.
Narration: when several rules match, the spec sets the priority: exact path first, then longest prefix, then the number of header matches.
On screen: 100 small dots flow to v1 and v2, with the counter at 90 to 10. The slider is dragged to 50 to 50.
Narration: backendRefs weights make a canary release a single patch operation, and rollback takes seconds too.
On screen: in the kubectl describe output, ResolvedRefs=False BackendNotFound is circled in red.
Narration: always check the status conditions: Accepted, Programmed, and ResolvedRefs. They tell you directly what's misconfigured.
Module 7 · NetworkPolicy
- Describe the default behavior (allow all), the isolation semantics once a Pod is selected, and how multiple policies combine as a union.
- Write combinations of podSelector, namespaceSelector, and ipBlock. Note the difference between AND within one element and OR across list items.
- Write the standard default-deny template (ingress and egress), and allow DNS egress.
- Understand cluster-level policies (AdminNetworkPolicy → ClusterNetworkPolicy) and the extended policies of Cilium and Calico.
What: NetworkPolicy is a Pod-level L3/L4 firewall
- Allow all by default: if no policy selects a Pod, its ingress and egress are unrestricted.
- Isolated once selected: if a policy's
podSelectorselects a Pod andpolicyTypesincludes Ingress, that Pod's ingress is limited to the sources listed in the policy. Egress works the same way. Ingress and egress are isolated separately. - Allow only, no deny: when multiple policies select the same Pod, they combine as a union, and order doesn't matter. You can't use standard NetworkPolicy to deny a specific source.
- Both sides must allow: a connection from A to B requires A's egress to allow B and B's ingress to allow A (if both sides are isolated). Return traffic is allowed automatically by connection tracking.
- Requires a CNI that enforces it: kindnet (kind ≥ v0.24.0), Calico, Cilium, Azure NPM, and others enforce policies. A CNI that doesn't support them silently ignores policy objects.
Why: why default deny
Allowing all by default means any compromised Pod (for example, an RCE in web) can scan the whole cluster laterally, connect directly to the database, and reach the cloud metadata endpoint (169.254.169.254). Default deny plus explicit allows limit the blast radius to the connections the business actually needs. It's the foundation of zero trust and of compliance requirements such as PCI DSS network segmentation.
How: selector semantics (where people most often make mistakes)
| Syntax | Meaning |
|---|---|
from: [{podSelector: {matchLabels: {app: web}}}] | Pods with app=web in the same namespace |
from: [{namespaceSelector: {matchLabels: {team: a}}}] | All Pods in the team=a namespace |
from: [{namespaceSelector: {…}, podSelector: {…}}] (one element) | AND: the specified Pods in the specified namespace |
from: [{namespaceSelector: {…}}, {podSelector: {…}}] (two elements) | OR: all Pods in the specified namespace, or the specified Pods in this namespace |
ipBlock: {cidr: 10.0.0.0/8, except: [10.1.0.0/16]} | IP ranges outside the cluster (using ipBlock for Pod IPs varies by implementation, not recommended) |
podSelector: {} | All Pods in this namespace |
ingress: [{}] / egress: [{}] | Allow all ingress / egress |
Every namespace automatically has the label kubernetes.io/metadata.name=<name>, which you can use in a namespaceSelector (for example, to select kube-system). For ports, use port + endPort for a range, or a named port.
When: cluster-level and extended policies
| Option | Scope | Capabilities | Status |
|---|---|---|---|
| NetworkPolicy | Namespace (application teams) | L3/L4 allow | GA, core API |
| AdminNetworkPolicy / BaselineAdminNetworkPolicy | Cluster (administrators) | Allow / Deny / Pass, priority | CRDs from the sig-network network-policy-api project (v1alpha1); the project page lists it as “Previous… no longer actively developed” |
| ClusterNetworkPolicy | Cluster (administrators) | Merges ANP and BANP into a single CRD with tiers | The project's only active API today: v0.2.0 introduced v1alpha2, and v0.3.0 moved to v1beta1 (v1alpha2 is still served). It's still a CRD, not a core API, and support depends on the CNI. |
| Calico NetworkPolicy / GlobalNetworkPolicy | Namespace / cluster | Deny, priority (order), tiers, host endpoints | Calico-specific |
| CiliumNetworkPolicy / CiliumClusterwideNetworkPolicy | Namespace / cluster | L7 (HTTP methods/paths, gRPC, Kafka), toFQDNs, identity-based | Cilium-specific |
Architecture diagram: zero-trust target topology for shop
Flow diagram: how a new connection is evaluated
Interactive matrix: select a policy combination to see which connections are allowed
Select the policies to apply to the shop namespace (matching the YAML on the Lab tab one-to-one). Matrix rows are sources and columns are destinations. ✓ means allowed, ✗ means denied. The DNS column shows whether Service names can be resolved.
Core commands
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl get networkpolicy -A | List policies (short name netpol) | — |
kubectl describe netpol NAME | Human-readable explanation of the rules | Check whether AND/OR behave as expected |
kubectl exec netshoot -- nc -zv -w 2 HOST PORT | Test TCP connectivity | Timeout = most likely dropped by a policy |
kubectl -n kube-system logs ds/kindnet | kindnet / kube-network-policies logs | Calico: calicoctl; Cilium: hubble observe --verdict DROPPED |
kubectl label ns NAME key=value | Label namespaces for namespaceSelector | Prefer the built-in kubernetes.io/metadata.name |
# 0) Default deny: select all Pods in shop for ingress and egress
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-all, namespace: shop}
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
---
# 1) Allow all Pods to reach cluster DNS (UDP + TCP 53)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: allow-dns-egress, namespace: shop}
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}
---
# 2) web: allow ingress from the Gateway data plane and the test client; allow egress to api
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: web-policy, namespace: shop}
spec:
podSelector: {matchLabels: {app: web}}
policyTypes: [Ingress, Egress]
ingress:
- from:
- namespaceSelector:
matchLabels: {kubernetes.io/metadata.name: envoy-gateway-system}
- podSelector: {matchLabels: {app: netshoot}}
ports:
- {protocol: TCP, port: 80}
egress:
- to:
- podSelector: {matchLabels: {app: api}}
ports:
- {protocol: TCP, port: 9898}
---
# 3) api: accept only web, the Gateway (/api route), and the test client; allow egress only to db
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: api-policy, namespace: shop}
spec:
podSelector: {matchLabels: {app: api}}
policyTypes: [Ingress, Egress]
ingress:
- from:
- podSelector: {matchLabels: {app: web}}
- podSelector: {matchLabels: {app: netshoot}}
- namespaceSelector:
matchLabels: {kubernetes.io/metadata.name: envoy-gateway-system}
ports:
- {protocol: TCP, port: 9898}
egress:
- to:
- podSelector: {matchLabels: {app: db}}
ports:
- {protocol: TCP, port: 5432}
---
# 4) db: accept only api
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: db-policy, namespace: shop}
spec:
podSelector: {matchLabels: {app: db}}
policyTypes: [Ingress]
ingress:
- from:
- podSelector: {matchLabels: {app: api}}
ports:
- {protocol: TCP, port: 5432}
---
# 5) netshoot (test client): allow egress to any Pod in shop (for the lab only)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: netshoot-egress, namespace: shop}
spec:
podSelector: {matchLabels: {app: netshoot}}
policyTypes: [Egress]
egress:
- to:
- podSelector: {}
How to verify: see the connectivity matrix script on the Lab tab. Common mistake: forgetting that the Gateway data plane is in another namespace, which causes 503 or timeouts on external access. Production use: use 0) and 1) as the baseline for every business namespace (they can be enforced uniformly through admission policies or GitOps templates).
egress:
- to:
- ipBlock:
cidr: 0.0.0.0/0
except: [169.254.169.254/32]
Lab 7: zero trust for shop (about 8 min)
cat > check.sh <<'EOF'
#!/usr/bin/env bash
NS=shop
pod() { kubectl -n $NS get pod -l app=$1 -o jsonpath='{.items[0].metadata.name}'; }
t() { # $1=source app $2=target host $3=port $4=description
if kubectl -n $NS exec $(pod $1) -c ${5:-$(kubectl -n $NS get pod $(pod $1) -o jsonpath='{.spec.containers[0].name}')} -- \
sh -c "nc -z -w 2 $2 $3" >/dev/null 2>&1; then r="✓"; else r="✗"; fi
printf "%-10s → %-28s %s\n" "$1" "$4" "$r"
}
t netshoot web 80 "web:80"
t netshoot api 9898 "api:9898"
t netshoot db 5432 "db:5432"
t web api 9898 "web→api:9898"
t web db 5432 "web→db:5432"
t api db 5432 "api→db:5432"
kubectl -n $NS exec $(pod netshoot) -- sh -c 'dig +short +time=2 +tries=1 api.shop.svc.cluster.local' | grep -q . && echo "DNS ✓" || echo "DNS ✗"
GW=$(kubectl -n $NS get gateway shop-gw -o jsonpath='{.status.addresses[0].value}')
code=$(curl -s -m 3 -o /dev/null -w '%{http_code}' -H 'Host: shop.example.test' http://$GW/api/version)
echo "external→Gateway→api HTTP $code"
EOF
chmod +x check.sh && ./check.sh
netshoot → web:80 ✓ netshoot → api:9898 ✓ netshoot → db:5432 ✓ web → web→api:9898 ✓ web → web→db:5432 ✓ ← should not be allowed! api → api→db:5432 ✓ DNS ✓ external→Gateway→api HTTP 200
Only the source Pod needs nc. netshoot has it built in, and nginx:1.29-alpine and podinfo (alpine-based) include busybox nc. If your image doesn't have nc or doesn't support -z, you can replace the t function with kubectl debug --target to attach a netshoot ephemeral container. Ephemeral containers share the Pod's network namespace and are subject to the same policies.
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-all, namespace: shop}
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
EOF
./check.sh
(all items ✗, DNS ✗, external→Gateway→api HTTP 503 or 000)
kubectl apply -f netpol-shop.yaml, apply allow-dns-egress separately, then run ./check.sh. DNS returns to ✓, but all TCP connections are still ✗. This shows that “being able to resolve names” doesn't mean “being able to connect.”kubectl apply -f netpol-shop.yaml kubectl -n shop get netpol ./check.sh
netshoot → web:80 ✓ netshoot → api:9898 ✓ netshoot → db:5432 ✗ web → web→api:9898 ✓ web → web→db:5432 ✗ ← lateral movement blocked api → api→db:5432 ✓ DNS ✓ external→Gateway→api HTTP 200
kubectl -n shop delete netpol --all.Case 1: every namespace gets baseline policies automatically
Problem: teams create new namespaces on their own and often forget default-deny.
Approach: a GitOps template (or a Kyverno generate rule) automatically creates default-deny-all + allow-dns-egress when a namespace is created. At the cluster level, use ClusterNetworkPolicy (if the CNI supports it), or Calico GlobalNetworkPolicy / CiliumClusterwideNetworkPolicy, to enforce rules teams can't override, such as “block access to 169.254.169.254” and “block cross-tenant namespace access.”
Case 2: allow access only to specific SaaS domains
Problem: the payment service may only egress to api.stripe.com, but its IPs change, and ipBlock can't keep up.
Approach: standard NetworkPolicy can't allow traffic by domain name. Use Cilium toFQDNs (with a DNS proxy), Calico Enterprise's DNS policies, or route traffic through an egress proxy or Azure Firewall's FQDN rules.
Case 3: choosing a policy engine on AKS
On AKS you can choose Azure Network Policy Manager, Calico, or Cilium (Azure CNI powered by Cilium) as the policy engine. Different engines support ipBlock, named ports, and logging/observability differently. Before switching engines, run connectivity regression tests using the check.sh approach from this lesson. For the exact support matrix, see Microsoft Learn's “Secure traffic between pods using network policies.”
Common errors and fixes
After applying default-deny: dial tcp: lookup api on 10.96.0.10:53: read udp …: i/o timeout
Cause: outbound DNS is denied.
Fix: Apply allow-dns-egress (UDP + TCP 53, targeting k8s-app=kube-dns in kube-system). If you use NodeLocal DNSCache, also allow its link-local address (usually ipBlock 169.254.20.10/32).
The policy is written but has no effect at all (web can still reach db)
Cause: the CNI does not enforce NetworkPolicy (such as Flannel), the kind version is too old (< v0.24.0), the policy is in the wrong namespace, or the podSelector label is misspelled.
kind version; kubectl -n kube-system get pods -o wide | grep -E 'kindnet|calico|cilium' kubectl -n shop describe netpol db-policy kubectl -n shop get pods -l app=db --show-labels
External access through the Gateway returns 503 upstream connect error or disconnect/reset before headers
Cause: the backend Pods' ingress does not allow traffic from the namespace where the Gateway data plane runs (envoy-gateway-system).
Fix: add namespaceSelector: kubernetes.io/metadata.name: envoy-gateway-system to the web/api policy (or, more precisely, add the labels of the Envoy Pods).
A Service port written in the policy has no effect: port 80 is allowed, but api actually listens on 9898
Cause: policies are evaluated after DNAT, so they see the Pod's target port.
Fix: use targetPort (the container port) or a named port (such as port: http) in the policy.
1. Write a policy that denies all ingress to the shop namespace only (egress is not affected).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-ingress, namespace: shop}
spec:
podSelector: {}
policyTypes: [Ingress]2. Test whether web Pods can reach db on port 5432 (2-second timeout).
kubectl -n shop exec deploy/web -- nc -z -w 2 db 5432 && echo OK || echo BLOCKED
Prometheus in the monitoring namespace needs to scrape /metrics from all Pods in shop (api on 9898). Under a zero-trust policy, what is the minimal allow rule? What should you watch out for?
Add this rule to the ingress of api-policy: from: [{namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: monitoring}}, podSelector: {matchLabels: {app.kubernetes.io/name: prometheus}}}], ports: [{protocol: TCP, port: 9898}]. The namespaceSelector and podSelector must be in the same element (AND). Otherwise, you allow the entire monitoring namespace, or every Pod with the Prometheus label in this namespace. If the monitoring namespace is also default-deny, you also need to give Prometheus an egress rule to shop on port 9898.
Verified teaching videos
Titles and channels were verified with the YouTube oEmbed API. No verified video covering ClusterNetworkPolicy was found.
Official documentation
- Network Policies
- sig-network network-policy-api (ClusterNetworkPolicy)
- kindnet Network Policies
- kind v0.24.0 release notes
Video storyboard
This course material cannot generate video or MP3 files directly, so storyboards and narration scripts are provided instead.
On screen: every Pod in the shop namespace is covered in connecting lines (everything reaches everything). A compromised web icon turns red, and its line extends to db.
Narration: By default, all Pods in Kubernetes can reach each other, so a compromised frontend can connect directly to the database.
On screen: default-deny drops in, and all lines disappear. Then three green lines appear one by one: DNS, web→api, and api→db.
Narration: Start with default-deny, then allow only what the business needs, one rule at a time. Don't forget to allow DNS.
On screen: two YAML blocks side by side: the same element (AND) and two elements (OR), with the difference in selected Pod sets highlighted below.
Narration: When namespaceSelector and podSelector are in the same element, it means "and." When they are in two separate elements, it means "or." This is the most common mistake.
Module 8 · Network Troubleshooting
- Master top-down layered troubleshooting. At each layer, use one or two commands to confirm or rule out the problem.
- Use
kubectl debugfluently (ephemeral containers with--target, node debugging) and the netshoot toolbox. - Recognize seven common failure types: selector mismatch, wrong targetPort, listening only on 127.0.0.1, NetworkPolicy not allowing DNS, slow ndots, MTU issues, and Gateway Accepted=False.
What: the layered troubleshooting model
| Layer | Question | Key commands | Symptoms |
|---|---|---|---|
| 1. DNS | Can the name be resolved? | dig +search api, getent hosts api | could not resolve host, i/o timeout … :53 |
| 2. Service | Does the Service exist, and are the port and targetPort correct? | kubectl get svc api -o yaml | Connection refused (when there are no endpoints) or a timeout |
| 3. EndpointSlice | Are there ready endpoints? | kubectl get endpointslices -l kubernetes.io/service-name=api | ENDPOINTS is empty / ready=false |
| 4. Pod | Is the app listening on the right address and port? | kubectl debug … --target + ss -lntp; connect directly to the Pod IP | Connection to the Pod IP is also refused |
| 5. CNI / policy | Do the Pod network and NetworkPolicy allow the traffic? | kubectl get netpol, cross-node ping, tcpdump | Timeout; works on the same node, fails across nodes |
| 6. Node | kube-proxy rules, conntrack, MTU, node firewall | nft list table ip kube-proxy, ping -M do -s | Small packets pass, large ones fail; some nodes are abnormal |
| 7. External | LB / Gateway / DNS records / cloud NSG | kubectl describe gateway/httproute, kubectl get svc -o wide | EXTERNAL-IP stuck at pending, Accepted=False, 404/503 |
Why: locate the layer first, then find the cause
Network problems look alike (“timeouts”, “can't connect”), but each layer is cheap to check. Checking layer by layer avoids two kinds of waste: searching for a network problem in application code, and searching for an application problem in the network layer (for example, an app listening only on 127.0.0.1). The bisection method works just as well: first connect directly from a client Pod to the backend Pod IP:port. If that succeeds, the problem is in the DNS/Service layer. If it fails, the problem is in the Pod/CNI/policy layer.
How: the toolbox
- netshoot (
nicolaka/netshoot:v0.16): dig, curl, nc, ss, ip, tcpdump, mtr, iperf3, termshark, and more. kubectl debug -it POD --image=nicolaka/netshoot:v0.16 --target=CONTAINERinjects an ephemeral container into a running Pod. It shares the network namespace.--targetalso shares the target container's process namespace, so you can see its processes. This works well with distroless images.kubectl debug node/NODE -it --image=…starts a debug Pod in the node's host network and PID namespaces. The host filesystem is mounted at/host(you can runchroot /host).kubectl get events --sort-by=.lastTimestampandkubectl describe: status and reasons.- Built-in CNI tools: Cilium
hubble observe, Calicocalicoctl, and Azureaz aksnetwork diagnostics (such as AKS connectivity diagnostics; follow Microsoft Learn for details).
When: quick reference for seven common failures
| Failure | One-line identification | Fix |
|---|---|---|
| Service selector mismatch | EndpointSlice is empty, but the Pod is running | Align the labels |
| Wrong targetPort | The endpoint exists, and a direct connection to the Pod's correct port works, but going through the Service times out or is refused | Correct the targetPort (named port recommended) |
| App listens only on 127.0.0.1 | curl localhost works inside the Pod, but direct connections to the Pod IP from other Pods are refused; ss -lnt shows 127.0.0.1:PORT | Change to 0.0.0.0 (or [::]) |
| NetworkPolicy missing DNS | Works by IP, fails by name; dig times out | allow-dns-egress |
| ndots causes slowness | The first packet to external domains is slow; CoreDNS logs show many NXDOMAIN responses | Add a trailing dot to FQDNs / ndots:2 / NodeLocal DNSCache |
| MTU | Small requests work; large responses or TLS handshakes hang | Unify the CNI MTU, and allow ICMP “fragmentation needed” |
| Gateway Accepted=False | Route exists but returns 404; status shows NotAllowedByListeners / RefNotPermitted | allowedRoutes / ReferenceGrant / hostname |
nc -z / curl). ② “Connection refused and timeout are the same.” Refused means the far end (or a kube-proxy reject rule) explicitly rejected the connection, usually because of the port or because there are no endpoints. A timeout often means the policy is dropping packets, or there is a routing or firewall problem. ③ “Restarting the Pod fixes network problems.” It may make the symptoms disappear for a while (new IP, new connections), but it hides the root cause.Decision flow: layered bisection
Architecture diagram: where the debug container goes
Layered troubleshooting drill: pick a failure and locate it layer by layer
Each layer shows real diagnostic commands and sample output. Stop at the first abnormal layer and apply the fix.
Core commands
| Command | Purpose | Key options / notes |
|---|---|---|
kubectl debug -it POD --image=nicolaka/netshoot:v0.16 --target=CTR | Inject an ephemeral container into a Pod | Ephemeral containers cannot be deleted and end with the Pod; requires RBAC pods/ephemeralcontainers |
kubectl debug POD -it --copy-to=dbg --image=… --share-processes | Copy a Pod to debug it (the original Pod is not affected) | Can also use --set-image to replace the image |
kubectl debug node/NODE -it --image=… | Node debugging | --profile=sysadmin for higher privileges (depends on kubectl version support) |
kubectl get endpointslices -l kubernetes.io/service-name=api | Endpoint check | -o yaml to view conditions |
kubectl get events -n shop --sort-by=.lastTimestamp | Recent events | --field-selector type=Warning |
tcpdump -ni eth0 port 9898 | Capture packets to confirm they arrive | Run in an ephemeral container or node debug Pod |
SVC=api; NS=shop
kubectl -n $NS get svc $SVC -o wide
kubectl -n $NS get endpointslices -l kubernetes.io/service-name=$SVC -o wide
kubectl -n $NS get pods -l "$(kubectl -n $NS get svc $SVC -o jsonpath='{.spec.selector}' | sed 's/[{}"]//g; s/:/=/g')" -o wide
kubectl -n $NS get netpol
kubectl -n $NS exec netshoot -- sh -c "dig +search +short $SVC; nc -zv -w 2 $SVC 9898"
NAME TYPE CLUSTER-IP PORT(S) SELECTOR api ClusterIP 10.96.142.17 9898/TCP app=api NAME ADDRESSTYPE PORTS ENDPOINTS api-7xkqp IPv4 9898 10.244.1.5,10.244.2.4,10.244.1.6 + 1 more… api-v1-… 1/1 Running 10.244.1.5 lab-worker … 10.96.142.17 Connection to api (10.96.142.17) 9898 port [tcp/*] succeeded!
kubectl -n shop debug -it deploy/api-v1 --image=nicolaka/netshoot:v0.16 --target=podinfo -- ss -lntp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 4096 *:9898 *:* users:(("podinfo",pid=1,fd=7))
LISTEN 0 4096 *:9999 *:* users:(("podinfo",pid=1,fd=8))
*:9898 means listening on all addresses. If it shows 127.0.0.1:9898, other Pods cannot reach it. kubectl debug deploy/… picks one Pod of the Deployment.
kubectl debug node/lab-worker -it --image=nicolaka/netshoot:v0.16 -- sh -c ' ip -br link | head; tcpdump -ni any -c 5 tcp port 9898' # Bisect the MTU from the client Pod (1472 = 1500 - 20 IP - 8 ICMP) kubectl -n shop exec netshoot -- ping -c 2 -M do -s 1472 10.244.2.5 kubectl -n shop exec netshoot -- ping -c 2 -M do -s 1400 10.244.2.5
kubectl -n shop get gateway,httproute kubectl -n shop describe httproute shop-api | sed -n '/Status/,$p' kubectl -n envoy-gateway-system logs deploy/envoy-gateway --tail=30
Lab 8: Fault injection and diagnosis (about 8 minutes)
kubectl -n shop patch svc api -p '{"spec":{"selector":{"app":"api-typo"}}}'
kubectl -n shop exec netshoot -- curl -s -m 3 api:9898/version; echo "exit=$?"
kubectl -n shop get endpointslices -l kubernetes.io/service-name=api # ENDPOINTS <unset>
kubectl -n shop patch svc api -p '{"spec":{"selector":{"app":"api"}}}' # restore
exit=7 ← curl: (7) Connection refused (no endpoints → reject) NAME ADDRESSTYPE PORTS ENDPOINTS AGE api-7xkqp IPv4 <unset> <unset> 40m
kubectl -n shop patch svc api --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":9999}]'
kubectl -n shop exec netshoot -- curl -s -m 3 api:9898/version; echo "exit=$?"
EP=$(kubectl -n shop get pod -l version=v1 -o jsonpath='{.items[0].status.podIP}')
kubectl -n shop exec netshoot -- curl -s -m 3 $EP:9898/version | head -3 # direct connection to the correct port works → Service-layer problem
kubectl -n shop get svc api -o jsonpath='{.spec.ports}'; echo
kubectl -n shop patch svc api --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":"http"}]'
Interestingly, podinfo also listens on 9999 (the gRPC port), so you may get an odd response instead of an error. “It connects but returns the wrong thing” is also a classic symptom of a wrong targetPort.
kubectl -n shop create deploy local-only --image=nginx:1.29-alpine
kubectl -n shop patch deploy local-only --type=json -p '[{"op":"add","path":"/spec/template/spec/containers/0/command","value":["sh","-c","sed -i \"s/listen *80;/listen 127.0.0.1:80;/\" /etc/nginx/conf.d/default.conf && exec nginx -g \"daemon off;\""]}]'
kubectl -n shop expose deploy local-only --port=80
kubectl -n shop rollout status deploy/local-only
kubectl apply -f - <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: local-only-ingress, namespace: shop}
spec:
podSelector: {matchLabels: {app: local-only}}
policyTypes: [Ingress]
ingress: [{}]
EOF
kubectl -n shop exec netshoot -- curl -s -m 3 local-only; echo "exit=$?" # 7 refused
kubectl -n shop exec deploy/local-only -- wget -qO- http://127.0.0.1 | head -2 # works inside the Pod
kubectl -n shop debug -it deploy/local-only --image=nicolaka/netshoot:v0.16 --target=nginx -- ss -lnt
exit=7 <!DOCTYPE html> <html> State Recv-Q Send-Q Local Address:Port LISTEN 0 511 127.0.0.1:80
Cleanup: kubectl -n shop delete deploy,svc local-only; kubectl -n shop delete netpol local-only-ingress.
kubectl -n shop get netpol allow-dns-egress -o yaml > dns-pol.yaml
kubectl -n shop delete netpol allow-dns-egress
kubectl -n shop exec netshoot -- curl -s -m 5 api:9898/version; echo "exit=$?" # 6 = cannot resolve
CIP=$(kubectl -n shop get svc api -o jsonpath='{.spec.clusterIP}')
kubectl -n shop exec netshoot -- curl -s -m 3 $CIP:9898/version | head -2 # works by IP
kubectl apply -f dns-pol.yaml
Note: netshoot's egress policy allows traffic to all Pods in shop, but CoreDNS runs in kube-system. So name resolution fails while IP access succeeds. This is the sign of a DNS-layer failure.
kubectl create ns team-b
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: reports, namespace: team-b}
spec:
parentRefs: [{name: shop-gw, namespace: shop}]
hostnames: ["shop.example.test"]
rules:
- matches: [{path: {type: PathPrefix, value: /reports}}]
backendRefs: [{name: web, namespace: shop, port: 80}]
EOF
kubectl -n team-b get httproute reports -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
Accepted=False (NotAllowedByListeners) ResolvedRefs=False (RefNotPermitted)
Two separate problems: the listener allows attachments only from the Same namespace, and the cross-namespace reference to shop/web is missing a ReferenceGrant. Cleanup: kubectl delete ns team-b.
Case 1: 10% of requests return 503 after a release
Symptom: a spike of 503s lasting 1–2 minutes during each release.
Diagnosis: 503 at the Gateway layer → terminating Pods still briefly appear in the EndpointSlice → the app receives SIGTERM and exits immediately.
Fix: add a preStop delay, graceful shutdown, and a sensible readinessProbe. On the Envoy side, enable retries (an implementation-specific policy, such as Envoy Gateway BackendTrafficPolicy).
Case 2: only Pods on one node time out when accessing the database
Diagnosis: direct connection to the Pod IP fails → only that node is affected → node debugging shows the conntrack table is full (nf_conntrack: table full, dropping packet).
Fix: raise nf_conntrack_max (kube-proxy conntrack.maxPerCore), find the application leaking connections, and enable connection pooling for high-concurrency services.
Case 3: “Intermittent DNS timeout” ticket on AKS
Diagnosis: CoreDNS metrics show 4 times the expected request volume (amplified by ndots), and the node's conntrack insert_failed count is rising.
Fix: adjust ndots, use NodeLocal DNSCache, and scale CoreDNS replicas with the node count. Set up a DNS latency alert (CoreDNS coredns_dns_request_duration_seconds).
Interactive network troubleshooting decision tree
Work through the symptoms step by step to get diagnostic commands and fix suggestions.
Common errors and fixes
error: ephemeral containers are disabled for this cluster / pods "x" is forbidden: … cannot patch resource "pods/ephemeralcontainers"
Cause: the current user lacks patch/update permission on pods/ephemeralcontainers (the ephemeral containers feature itself has been GA since v1.25).
Fix: grant that subresource permission to the troubleshooting role, or use kubectl debug --copy-to (requires create pods permission).
curl: (56) Recv failure: Connection reset by peer (intermittent, through a Service)
Cause: the backend restarted or was deleted mid-connection, the app's keepalive timeout is shorter than the client's, the conntrack entry was cleaned up, or the node's conntrack table is full.
kubectl -n shop get pods -l app=api -o wide # RESTARTS? kubectl debug node/lab-worker -it --image=nicolaka/netshoot:v0.16 -- sh -c 'cat /proc/sys/net/netfilter/nf_conntrack_count /proc/sys/net/netfilter/nf_conntrack_max'
Large file downloads or TLS handshakes hang, while small requests work
Cause: MTU mismatch (overlay, VPN, cloud network), and ICMP Fragmentation Needed messages are dropped, so PMTUD does not work.
kubectl -n shop exec netshoot -- ip link show eth0 | grep mtu kubectl -n shop exec netshoot -- ping -c 2 -M do -s 1472 <peer-PodIP>
Fix: configure the correct MTU in the CNI; allow ICMP type 3 code 4.
1. Inject a netshoot ephemeral container into one Pod of the api-v1 Deployment, and check which ports it listens on.
kubectl -n shop debug -it deploy/api-v1 --image=nicolaka/netshoot:v0.16 --target=podinfo -- ss -lntp
2. List the recent Warning events in the shop namespace, sorted by time.
kubectl -n shop get events --field-selector type=Warning --sort-by=.lastTimestamp
web calls api and gets “i/o timeout”. The api Pods are all Running and Ready, and the EndpointSlice is normal. What are your next three steps?
① From a web Pod (or a debug Pod with the same labels), connect directly to the api Pod IP:9898. If it times out, the problem is in the Pod/network/policy layer. ② Check NetworkPolicy: whether web's egress allows app=api:9898, whether api's ingress allows app=web, and whether DNS is allowed (a timeout rather than a refusal strongly suggests the policy is dropping packets). ③ Determine whether the traffic crosses nodes. If it works on the same node but fails across nodes, check CNI routes, the encapsulation port, and MTU (node debugging plus tcpdump to see whether packets reach the target node).
Verified teaching video
Titles and channels were verified with the YouTube oEmbed API. No verified video was found that specifically covers the kubectl debug + netshoot troubleshooting workflow.
Official documentation
- Debug Services
- Debug Running Pods (ephemeral containers)
- Debugging Kubernetes Nodes With Kubectl
- netshoot
Video storyboard
This course material cannot generate video or MP3 files directly, so storyboards and narration scripts are provided instead.
On screen: seven vertical cards for DNS, Service, EndpointSlice, Pod, CNI and policy, node, and external. A magnifying glass moves down from the top.
Narration: Troubleshoot networking from top to bottom, through seven layers. At each layer, use one or two commands to confirm or rule it out.
On screen: a knife splits the problem space in two: “direct connection to the Pod IP succeeds” and “fails”.
Narration: The first cut is always to bypass the Service and connect directly to the Pod IP. It cuts the problem space in half.
On screen: kubectl debug inserts a small netshoot box into the side of a Pod. The box shows ss output, with 127.0.0.1:80 circled in red.
Narration: An ephemeral container shares the Pod's network, so you can see the address the app is really listening on. Listening only on the loopback address is one of the easiest causes to overlook.
Command cheat sheet
Pod networking and CNI
kubectl get pods -o wide kubectl get nodes -o custom-columns=N:.metadata.name,CIDR:.spec.podCIDR docker exec lab-worker ip route # kind node docker exec lab-worker ls /etc/cni/net.d /opt/cni/bin kubectl debug node/NODE -it --image=nicolaka/netshoot:v0.16 kubectl debug -it POD --image=nicolaka/netshoot:v0.16 --target=CTR -- ip -br addr
Service / kube-proxy
kubectl get svc,endpointslices -l kubernetes.io/service-name=SVC
kubectl -n kube-system get configmap kube-proxy -o jsonpath='{.data.config\.conf}' | grep mode
docker exec lab-worker nft list table ip kube-proxy | grep NS/SVC
docker exec lab-worker iptables-save -t nat | grep KUBE-SVC
kubectl patch svc SVC -p '{"spec":{"trafficDistribution":"PreferSameZone"}}'
kubectl patch svc SVC -p '{"spec":{"sessionAffinity":"ClientIP"}}'DNS
kubectl exec POD -- cat /etc/resolv.conf
kubectl exec netshoot -- dig +search +short SVC
kubectl exec netshoot -- dig +short POD-0.HEADLESS.NS.svc.cluster.local
kubectl exec netshoot -- dig +short SRV _http._tcp.SVC.NS.svc.cluster.local
kubectl exec POD -- getent hosts NAME
kubectl -n kube-system get cm coredns -o jsonpath='{.data.Corefile}'
kubectl -n kube-system logs -l k8s-app=kube-dns --tail=50LoadBalancer / NodePort
kubectl expose deploy D --type=LoadBalancer --port=80 --target-port=http
kubectl get svc -w
kubectl patch svc S -p '{"spec":{"externalTrafficPolicy":"Local"}}'
kubectl get svc S -o jsonpath='{.spec.healthCheckNodePort}'
curl -s http://NODEIP:HCNP/healthz
# AKS internal LB annotation
# service.beta.kubernetes.io/azure-load-balancer-internal: "true"Ingress migration
kubectl get ingressclass; kubectl get ingress -A kubectl get ingress -A -o yaml | grep -o 'nginx.ingress.kubernetes.io/[a-z0-9-]*' | sort | uniq -c go install github.com/kubernetes-sigs/ingress2gateway@v1.0.0 ingress2gateway print --providers=ingress-nginx -A > gw.yaml ingress2gateway print --providers=ingress-nginx --input-file=ing.yaml
Gateway API
kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.3/standard-install.yaml
kubectl get gatewayclass,gateway,httproute,grpcroute,referencegrant -A
kubectl wait --for=condition=Programmed gateway/GW --timeout=2m
kubectl get gateway GW -o jsonpath='{.status.addresses[0].value}'
kubectl get httproute R -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
curl -H 'Host: HOST' http://$GW/PATH
curl -sk --resolve HOST:443:$GW https://HOST/PATHNetworkPolicy
kubectl get netpol -A kubectl describe netpol NAME kubectl exec SRC -- nc -z -w 2 DST PORT && echo OK || echo BLOCKED kubectl label ns NS team=x kubectl -n kube-system logs ds/kindnet --tail=50 # Select kube-system: namespaceSelector.matchLabels.kubernetes.io/metadata.name: kube-system
Troubleshooting
kubectl get events -n NS --sort-by=.lastTimestamp kubectl debug -it deploy/D --image=nicolaka/netshoot:v0.16 --target=CTR -- ss -lntp kubectl debug POD -it --copy-to=dbg --image=nicolaka/netshoot:v0.16 --share-processes kubectl exec netshoot -- curl -v -m 3 SVC:PORT kubectl exec netshoot -- ping -c2 -M do -s 1472 PODIP kubectl debug node/N -it --image=nicolaka/netshoot:v0.16 -- tcpdump -ni any port PORT -c 10
Quick troubleshooting table
| Symptom | What to check first | Common causes |
|---|---|---|
| Connection refused (through a Service) | kubectl get endpointslices -l kubernetes.io/service-name=X | Selector mismatch, Pod not ready, app listening only on 127.0.0.1 |
| Timeout | Connect directly to the Pod IP; kubectl get netpol | NetworkPolicy drops, cross-node routing/encapsulation, wrong targetPort |
| could not resolve host | dig +search X; check the DNS policy | UDP/TCP 53 not allowed, CoreDNS problem, wrong namespace name |
| First packet to external domains is slow | Check CoreDNS logs for NXDOMAIN | ndots:5 + search expansion |
| EXTERNAL-IP pending | kubectl describe svc | No LB controller (kind not running cloud-provider-kind), cloud permissions/quota |
| Backend sees the node IP | Check externalTrafficPolicy | Cluster-mode SNAT, or a proxy-type LB in front |
| Gateway 404 | Route status, Host header | Hostname mismatch, Accepted=False (NotAllowedByListeners) |
| Gateway 500/503 | Route ResolvedRefs, backend policy | BackendNotFound, RefNotPermitted, NetworkPolicy does not allow the Gateway namespace |
| Large packets hang | ping -M do -s | MTU (overlay/VPN) |
For the complete interactive troubleshooting flow, see Module 8 → Troubleshooting → Decision tree.
Recommended config snippets
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-all}
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: allow-dns-egress}
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}apiVersion: v1
kind: Service
metadata: {name: api}
spec:
selector: {app: api}
ports:
- {name: http, port: 80, targetPort: http} # named port
trafficDistribution: PreferSameZone
---
# Pod spec fragment: a service with heavy access to external FQDNs
spec:
dnsConfig:
options:
- {name: ndots, value: "2"}
containers:
- name: app
ports:
- {name: http, containerPort: 8080}
lifecycle:
preStop:
exec: {command: ["sleep", "10"]}Capstone lab + final quiz
kubectl get nodes
kubectl get gatewayclass eg
kubectl -n shop get deploy,sts,svc
kubectl -n shop get secret shop-tls || {
openssl req -x509 -nodes -newkey rsa:2048 -days 30 -keyout shop.key -out shop.crt \
-subj "/CN=shop.example.test" -addext "subjectAltName=DNS:shop.example.test"
kubectl -n shop create secret tls shop-tls --cert=shop.crt --key=shop.key; }kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata: {name: shop-gw, namespace: shop}
spec:
gatewayClassName: eg
listeners:
- name: http
protocol: HTTP
port: 80
hostname: shop.example.test
allowedRoutes: {namespaces: {from: Same}}
- name: https
protocol: HTTPS
port: 443
hostname: shop.example.test
tls:
mode: Terminate
certificateRefs: [{kind: Secret, name: shop-tls}]
allowedRoutes: {namespaces: {from: Same}}
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: https-redirect, namespace: shop}
spec:
parentRefs: [{name: shop-gw, sectionName: http}]
hostnames: ["shop.example.test"]
rules:
- filters:
- type: RequestRedirect
requestRedirect: {scheme: https, statusCode: 301}
EOF
kubectl -n shop wait --for=condition=Programmed gateway/shop-gw --timeout=2m
GW=$(kubectl -n shop get gateway shop-gw -o jsonpath='{.status.addresses[0].value}'); echo GW=$GWkubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: shop-web, namespace: shop}
spec:
parentRefs: [{name: shop-gw, sectionName: https}]
hostnames: ["shop.example.test"]
rules:
- matches: [{path: {type: PathPrefix, value: /}}]
backendRefs: [{name: web, port: 80}]
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: shop-api, namespace: shop}
spec:
parentRefs: [{name: shop-gw, sectionName: https}]
hostnames: ["shop.example.test"]
rules:
- matches:
- path: {type: PathPrefix, value: /api}
headers: [{type: Exact, name: x-canary, value: "true"}]
filters:
- {type: URLRewrite, urlRewrite: {path: {type: ReplacePrefixMatch, replacePrefixMatch: /}}}
backendRefs: [{name: api-v2, port: 9898}]
- matches: [{path: {type: PathPrefix, value: /api}}]
filters:
- {type: URLRewrite, urlRewrite: {path: {type: ReplacePrefixMatch, replacePrefixMatch: /}}}
backendRefs:
- {name: api-v1, port: 9898, weight: 90}
- {name: api-v2, port: 9898, weight: 10}
EOF
for r in https-redirect shop-web shop-api; do echo "== $r"; kubectl -n shop get httproute $r -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'; donekubectl apply -f netpol-shop.yaml ./check.sh # the m7 connectivity matrix script (its external check uses HTTP, so it returns 301)
R="--resolve shop.example.test:443:$GW"
curl -s -o /dev/null -w 'HTTP %{http_code} -> %{redirect_url}\n' -H 'Host: shop.example.test' http://$GW/api/
curl -sk $R https://shop.example.test/ ; echo
for i in $(seq 1 200); do curl -sk $R https://shop.example.test/api/ | grep -o 'v[12]'; done | sort | uniq -c
curl -sk $R -H 'x-canary: true' https://shop.example.test/api/ | grep -o '"message": "[^"]*"'
kubectl -n shop exec deploy/web -c nginx -- nc -z -w 2 db 5432 && echo "web→db allowed ✗ fail" || echo "web→db denied ✓"
HTTP 301 -> https://shop.example.test/api/
shop web OK from web-6d8f9c7b4-x2v9q
179 v1
21 v2
"message": "shop api v2 (canary)"
web→db denied ✓# A: policy blocks the Gateway namespace
kubectl -n shop patch netpol web-policy --type=json -p '[{"op":"remove","path":"/spec/ingress/0/from/0"}]'
# B: api-v2 Service has a wrong targetPort
kubectl -n shop patch svc api-v2 --type=json -p '[{"op":"replace","path":"/spec/ports/0/targetPort","value":9999}]'
# C: certificate Secret is deleted
kubectl -n shop delete secret shop-tls
# D: DNS policy is deleted (web's nginx cannot resolve the upstream on its next restart)
kubectl -n shop delete netpol allow-dns-egress && kubectl -n shop rollout restart deploy/web
Hints: A → external HTTPS access returns 503; B → only 10% of requests and x-canary requests fail; C → https listener ResolvedRefs=False (InvalidCertificateRef); D → new web Pods in CrashLoopBackOff, with logs showing host not found in upstream "api.shop.svc.cluster.local". Recovery: re-apply the matching YAML / recreate the Secret.
kind delete cluster --name lab; docker rm -f cloud-provider-kind.Open-ended self-check (answer on your own first, then expand the reference answer)
1. Why does Kubernetes require NAT-free communication between Pods? What does this give NetworkPolicy?
Without NAT, each Pod's source IP is visible as-is inside the cluster, so applications don't need port coordination. NetworkPolicy can therefore allow traffic precisely by Pod identity (labels → IPs), without dealing with addresses hidden behind NAT.
2. Which components does curl api:9898 pass through, in order?
libc resolution (search + ndots) → CoreDNS (DNAT through the kube-dns Service) returns the ClusterIP → the client node's kernel nftables/iptables rules randomly pick a backend and DNAT to it, with conntrack recording the flow → Pod network (veth, routes, or encapsulation) to the backend node → the target Pod's eth0 (both sides' NetworkPolicies are evaluated along the way) → replies are translated back in reverse by conntrack.
3. What problem does externalTrafficPolicy: Local solve? What is the cost?
It preserves the client source IP and avoids an extra hop. The cost: nodes without local Pods must be removed by the LB health check (healthCheckNodePort), and spreading traffic per node can lead to uneven load across Pods.
4. Explain to management the impact of the ingress-nginx retirement and the actions required.
The Ingress API is still available, but the ingress-nginx controller was archived on 2026-03-24 and no longer receives security fixes. The ingress is the most exposed component, so you must migrate to a Gateway API implementation (or a controller that is still maintained). Use ingress2gateway to generate a draft, validate in parallel, and switch over one domain at a time. AKS managed NGINX support lasts until 2026-11.
5. In the Gateway API, what do allowedRoutes and ReferenceGrant each control?
allowedRoutes is set by the Gateway owner and controls “which namespaces' Routes can attach to this listener.” ReferenceGrant is set by the owner of the referenced resource and controls “which objects in other namespaces can reference my Service/Secret.”
6. After default-deny, what are the three types of traffic most often forgotten?
① DNS (UDP + TCP 53 to kube-system/CoreDNS); ② from the ingress data plane (the namespace of the Gateway/Ingress controller) to the backends; ③ monitoring scrapes (Prometheus) and health checks / sidecar-related traffic. Also remember egress to external dependencies (database FQDNs, SaaS).
Final quiz (12 questions, covering all modules)
Sources and versions
| Topic | Verification result | Source (page date / access date) |
|---|---|---|
| Kubernetes version | 1.37 latest patch is 1.37.1 (2026-09-15); 1.36 and 1.35 are supported; 1.34 is EOL | kubernetes.io/releases (accessed 2026-11-15) |
| v1.37 networking changes | nftables backend GA in v1.33, switched to netlink in v1.37; ipvs deprecated; kube-dns deprecated | v1.37 release blog (2026-08-26) |
| kube-proxy modes | In 1.37 the default is still iptables (it will change to nftables in the future). The ipvs feature is “Deprecated since v1.35,” disabled by default in v1.40 (recoverable via the KubeProxyIPVS feature gate), and removed in v1.43. nftables requires kernel ≥ 5.13, and NodePort defaults to --nodeport-addresses primary. | Virtual IPs and Service Proxies (accessed 2026-11-15) |
| Service fields | trafficDistribution values PreferSameZone / PreferSameNode / PreferClose (PreferClose is a deprecated alias); internalTrafficPolicy Stable since v1.26; sessionAffinity timeout defaults to 10800 seconds; NodePort default range 30000–32767 (static range 30000–30085); allocateLoadBalancerNodePorts and loadBalancerClass Stable since v1.24; Host/TLS warnings for ExternalName | Service, Virtual IPs (accessed 2026-11-15) |
| DNS | agnhost:2.39 dnsutils example; resolv.conf search/ndots:5; SRV and Pod record formats; CoreDNS keeps the kube-dns names and labels | Debugging DNS Resolution, DNS for Services and Pods (accessed 2026-11-15) |
| kind and NetworkPolicy | kind v0.24.0 release notes: “Out-of-the-box support for network policy via sigs.k8s.io/kube-network-policies”; kindnet docs: NetworkPolicy is implemented on top of kube-network-policies and supports Admin Network Policies; kind supports kubeProxyMode iptables / nftables / ipvs / none, and disableDefaultCNI can be used with Calico | kind v0.24.0, kindnet Network Policies, kind Configuration (accessed 2026-11-15) |
| Calico | Latest is 3.33 (v3.33.0); kind guide podSubnet 192.168.0.0/16; K8s ≥ 1.36 uses v3_projectcalico_org.yaml + tigera-operator.yaml + custom-resources.yaml, or calico.yaml | Calico on kind (accessed 2026-11-15) |
| cloud-provider-kind | go install / brew / container image (since v0.4.0, registry.k8s.io/cloud-provider-kind/cloud-controller-manager); the control plane must remove the exclude-from-external-load-balancers label | README (accessed 2026-11-15) |
| Gateway API | v1.6.0 (2026-06-29/30), v1.6.1 (07-16), v1.6.2 (09-03), v1.6.3 (10-06); v1.7.0 was released on 10-29 (this hour pins v1.6.3); TCPRoute/UDPRoute reached Standard in v1.6 | Releases, v1.6 blog (accessed 2026-11-15) |
| Envoy Gateway | v1.10.0; helm install eg oci://docker.io/envoyproxy/gateway-helm --version v1.10.0 -n envoy-gateway-system --create-namespace; the chart bundles Gateway API CRDs from the Experimental channel by default. You can manage the CRDs separately with gateway-crds-helm, or use --set crds.enabled=false. Before upgrading, raise the Gateway API CRDs to v1.6 first. | Install with Helm (accessed 2026-11-15) |
| Ingress and ingress-nginx | Ingress API is GA, has no removal plan, and is frozen; the project recommends Gateway. ingress-nginx was archived on 2026-03-24, with final version v1.15.1 | Ingress Controllers (accessed 2026-11-15), retirement announcement (2025-11-12) |
| ingress2gateway | v1.0.0; go install github.com/kubernetes-sigs/ingress2gateway@v1.0.0; print --providers=… [--namespace|-A|--input-file]; providers: apisix, cilium, ingress-nginx, istio, gce, kong, nginx, openapi, traefik | README (accessed 2026-11-15) |
| AKS Application Routing | Managed NGINX is based on upstream ingress-nginx, with Microsoft critical security patch support through 2026-11. The Gateway API implementation uses GatewayClass approuting-istio (deploys the Istio control plane, sidecarless); --enable-gateway-api --enable-app-routing-istio; enabled by default on new AKS 1.36+ Automatic clusters | app-routing (ms.date 2026-10-26), app-routing-gateway-api (ms.date 2026-08-31, updated 2026-11-06) |
| AKS internal LB | azure-load-balancer-internal, -internal-subnet, -ipv4, and azure-pls-create annotations; Basic LB has not been supported since 2025-09-30 | internal-lb (ms.date 2026-07-31) |
| Cluster-wide network policy | network-policy-api project: ANP/BANP are listed as Previous (no longer actively developed); ClusterNetworkPolicy is Active, introduced as v1alpha2 in v0.2.0 and upgraded to v1beta1 in v0.3.0 | network-policy-api, Releases (accessed 2026-11-15) |
| netshoot | Latest tag v0.16 (Docker Hub, 2026-07-01) | Docker Hub (accessed 2026-11-15) |
Video verification notes
All videos were checked one by one with the YouTube oEmbed API (which returns the title and channel name), confirming that the video IDs, titles, and authors match (2026-11-15): Michael Rubin, “Life of a Packet [I]” (CNCF, 0Omvgd7Hg1I); TechWorld with Nana, “Pods and Containers - Kubernetes Networking” (5cNrTU6o3Fw), “Kubernetes Services explained” (T4Z7visMM4E), “Kubernetes Ingress Tutorial for Beginners” (80Ew_fsV4rM); CNCF, “Kubernetes and Networks: Why is This So Dang Hard?” (GgCA2USI5iQ), “Scale the Internet with DNS: A CoreDNS Deep Dive” (bfUzLOFwns8), “CNCF On-Demand: Zero-Downtime Migration - Ingress NGINX to Envoy Gateway” (orO2_jLV720); Technical Cloud Knowledge, “Kubernetes CNI Deep Dive” (b-v-QQWT7vE); MattOps, “How Kubernetes Services Really Work” (-CQLSXpvM_Q); The Learning Channel, “Kubernetes kube-proxy Modes: iptables and ipvs” (lkXLsD6-4jA); Lachlan Evenson, “Using CoreDNS with Kubernetes” (whEZn7wmrDc); CodeLucky, “DNS in Kubernetes” (eKLfqAwMMGM); Anton Putra, “Kubernetes Networking: NodePort, LoadBalancer, Ingress, or Gateway API?” (LepslIb2me0); solo.io, “Migrating from Ingress to Gateway API” (lvssF97uDVA); Google Open Source, “The Kubernetes Gateway API: Concepts” (hqkPbW9RfD8); KodeKloud, “Gateway API Explained” (xaZ87iSvMAI); kgateway, “Demo: Exploring Gateway API's HTTP Routing Rules” (CGF3aZXOyxc); DevOps & AI Toolkit, “Kubernetes Network Policies Explained” (18FEA5xXBGY); Kubesimplify, “Kubernetes Network Policy Deep Dive” (Fr-6oDHbobM). The oEmbed endpoint does not return duration or publish date, so those are not listed. All of these videos are in English. Most were recorded before v1.37, Gateway API v1.6, and the ingress-nginx retirement, so for version details, follow this hour and the official docs. No verifiable high-quality video in Chinese was found.
Voice narration notes
The “Voice” tab reads the narration script aloud with the browser's Web Speech API (speechSynthesis, English voice, en-US), and English terms are pronounced with en-US. Results depend on the English voices installed on your system (for example, Microsoft Zira or David on Windows, or Samantha on macOS). This course material cannot embed MP3 files: the build environment cannot reach a TTS service. For offline audio, give the narration script to a TTS service such as Azure AI Speech. The “Video” tab of each module provides a storyboard that you can hand to a video generation tool.
Known limitations and conservative handling
- IPs, Pod name suffixes, hashes, port numbers (such as nodePort and healthCheckNodePort), counts, and times in the “expected output” are example values. nftables rule chain names and formats change with the kube-proxy version, so use the actual output as the reference.
- The cloud-provider-kind image tag is written from v0.4.0, the starting version mentioned in the README. Newer versions were not checked individually; confirm on the Releases page and replace the tag if needed.
- The
--set crds.enabled=falseflag and the gateway-crds-helm parameters for Envoy Gateway follow its v1.10 installation docs. The labels (gateway.envoyproxy.io/owning-gateway-name) and naming format of Envoy data-plane resources depend on the actual version. - The feature stages (Beta/GA version numbers) for each trafficDistribution value were not found as explicit FEATURE STATE lines in the official pages, so this hour only states “supported in 1.37.”
- The apiVersion for TCPRoute/UDPRoute after they reach Standard is not hard-coded; use
kubectl explain tcprouteas the reference. ReferenceGrant is written as v1beta1. - The contents of the kindnet CNI conflist and the IPAM storage path change between versions; the command output is illustrative.
- The AKS add-on parameters (Azure CNI Overlay, Cilium data plane) are for reference only. Follow
az aks create --helpand Microsoft Learn for the commands. - The weighted sampling and connection distribution in the animations are simulations, not performance test data.