Stage 7, Part 2 of 9 · p. 57, Kubernetes Networking Deep Dive

PART 2: ADVANCED CONCEPTS

6. CNI Deep Dive

Flannel (Simple Overlay)

AspectDetails
ApproachVXLAN overlay
Policy❌ None
PerformanceGood, but encapsulation overhead
Use CaseK3s default, simple clusters

Flannel's design philosophy is "do one thing well." A user-space daemon manages subnet allocation, while the kernel's VXLAN and bridge code handles forwarding. No policy, no observability — just connectivity.

Calico (Policy Powerhouse)

AspectDetails
ApproachBGP routing, iptables/eBPF
Policy✅ Excellent NetworkPolicy
PerformanceExcellent (no encapsulation by default)
Use CaseProduction, policy-heavy

Calico supports multiple data planes — iptables, nftables, eBPF, Windows HNS, and VPP — allowing operators to choose the best fit. The control plane includes Felix (per-node agent) and BIRD (BGP daemon).

Cilium (eBPF Native)

AspectDetails
ApproacheBPF (kernel-native)
Policy✅ L3/L4/L7
PerformanceBest (O(1) lookups)
Use CaseModern, high-performance

Cilium was purpose-built around eBPF. Every packet passes through eBPF programs attached to network interfaces. The architecture consists of:

Cilium's policy model is identity-based rather than IP-based. Pods are assigned cryptographic identities derived from Kubernetes labels, service accounts, and namespaces. Policies survive pod rescheduling and IP changes.

AWS VPC CNI

AspectDetails
ApproachNative VPC IPs
Policy✅ (via Calico)
PerformanceExcellent (native VPC)
Use CaseAWS EKS

The Amazon VPC CNI assigns pods real VPC IP addresses, enabling native VPC networking. Security groups, NACLs, and flow logs all work natively.

Two components:

Modes:

ModeIP UsagePod Density
Secondary IP (default)1 IP per podLimited by ENI × IPs
Prefix Delegation/28 prefix per ENI slot~4-16× more pods
Custom NetworkingDifferent subnet for podsSeparate CIDR

Prefix Delegation assigns /28 prefixes (16 IPs each) to ENI slots, dramatically increasing pod density. With prefix mode, an m5.large can support 110 pods vs 29 in secondary IP mode.

CNI Comparison Table

CNIApproachPolicyPerformanceBest For
FlannelVXLAN overlay❌GoodSimple clusters
CalicoBGP, iptables/eBPF✅ FullExcellentPolicy-heavy
CiliumeBPF✅ L3/L4/L7BestModern, high-performance
AWS VPC CNINative VPC✅ (via Calico)ExcellentEKS
Azure CNINative VNET✅ExcellentAKS
GKE Dataplane V2Cilium-based✅BestGKE

7. Cilium and eBPF

Why eBPF Changes Everything

Traditional networking (iptables) uses linear rule chains. eBPF uses hash tables with O(1) lookups. The time to resolve a service is constant regardless of whether you have 10 or 10,000 services.

Cilium Architecture

text
┌─────────────────────────────────────────────────────────────┐
│                    CILIUM ARCHITECTURE                      │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Cilium Agent (DaemonSet)                           │   │
│  │  • Watches K8s API for Pods, Services, Policies      │   │
│  │  • Compiles policies into eBPF programs             │   │
│  │  • Loads programs into kernel                       │   │
│  └──────────────────────┬──────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  eBPF Programs (attached to veth interfaces)        │   │
│  │  • Process packets at TC/XDP hooks                  │   │
│  │  • O(1) map lookups                                 │   │
│  │  • Identity-based policies                          │   │
│  └─────────────────────────────────────────────────────┘   │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Hubble (Observability)                             │   │
│  │  • Real-time flow visibility                        │   │
│  │  • DNS query logging                                │   │
│  │  • L7 protocol inspection                           │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

Cilium vs Calico Performance

Benchmarks show Cilium delivers approximately 25% higher throughput in service routing scenarios.

MetricCilium (eBPF)Calico (iptables)
Service routingO(1)O(n)
Throughput25% higherBaseline
CPU at scaleStableIncreases
LatencyLowerHigher

Cilium Features

FeatureDescription
kube-proxy replacementeBPF service load balancing
L7 policiesHTTP, gRPC, Kafka
HubbleFlow-level observability
Cluster MeshMulti-cluster networking
Service MeshSidecarless mesh
Runtime securityTetragon

Kernel Requirements

Cilium requires Linux kernel 4.19.57 or newer for full eBPF functionality. Modern managed Kubernetes (GKE, AKS, EKS) all meet this requirement.


8. kube-proxy Replacement with eBPF

Why Replace kube-proxy

Traditional kube-proxy modes have scaling issues:

How eBPF Replacement Works

eBPF-based implementations attach directly to network interfaces and cgroups, processing service traffic before the normal kube-proxy datapath. Service lookups use eBPF maps with O(1) complexity. Connection tracking happens in eBPF maps rather than iptables state.

Installing Cilium with kube-proxy Replacement

bash
# Initialize without kube-proxy
kubeadm init --skip-phases=addon/kube-proxy \
  --pod-network-cidr=10.244.0.0/16

# Install Cilium
helm repo add cilium https://helm.cilium.io/
helm install cilium cilium/cilium \
  --namespace kube-system \
  --set kubeProxyReplacement=true \
  --set k8sServiceHost=API_SERVER_IP \
  --set k8sServicePort=API_SERVER_PORT \
  --set bpf.masquerade=true \
  --set ipam.mode=kubernetes

Verifying the Replacement

bash
# Check Cilium status
kubectl -n kube-system exec ds/cilium -- cilium-dbg status | grep KubeProxyReplacement
# Should show: KubeProxyReplacement: True

# Verify no kube-proxy pods
kubectl get pods -n kube-system -l k8s-app=kube-proxy
# Should return no resources

Benefits of eBPF Replacement

BenefitDescription
O(1) service lookupConstant regardless of service count
No conntrack raceEliminates UDP DNS timeout
DSR supportDirect Server Return
Maglev hashingBetter load distribution
Session affinity without conntrackSimpler, faster
Faster failoverEndpoint changes propagate faster

9. NetworkPolicy

NetworkPolicy is the Kubernetes firewall for Pods.

Default Behavior

By default, all Pods can talk to all Pods. This is a security risk.

The Default Deny Pattern

The core best practice is to default-deny all traffic and then explicitly allow only what each workload needs. Apply default-deny for both ingress and egress in each namespace.

Default Deny All

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: production
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  - Egress

Empty podSelector: {} = all Pods in the namespace.

Allow Specific Ingress

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-frontend-to-backend
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: frontend
    ports:
    - protocol: TCP
      port: 8080

Allow Specific Egress

yaml
spec:
  podSelector:
    matchLabels:
      app: backend
  policyTypes:
  - Egress
  egress:
  - to:
    - namespaceSelector:
        matchLabels:
          name: kube-system
    ports:
    - protocol: UDP
      port: 53

NetworkPolicy Best Practices

PracticeWhy
Start with default deny per namespaceFoundation of zero-trust
Label everything consistentlyPolicies rely on selectors
Test in monitor mode firstAvoid breaking traffic
Enforce both ingress and egressEgress prevents exfiltration
Review effective policy regularlyDetect drift
Never flip the whole cluster at onceRoll out per namespace

NetworkPolicy Limitations

Native NetworkPolicies operate at L3/L4. They cannot:

For L7 policies, you need Cilium NetworkPolicy.


10. Cilium NetworkPolicy (L7 Policies)

CiliumNetworkPolicy extends NetworkPolicy with L7 (application layer) rules.

L7 HTTP Policy

yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: allow-http-get
spec:
  endpointSelector:
    matchLabels:
      app: backend
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: frontend
    toPorts:
    - ports:
      - port: "8080"
        protocol: TCP
      rules:
        http:
        - method: "GET"
          path: "/api/.*"

This allows only GET requests to /api/*.

gRPC Policy

Cilium treats gRPC as HTTP/2 traffic. Each gRPC method maps to an HTTP POST path such as /package.Service/Method. Cilium's HTTP L7 policy engine can match and filter gRPC calls using path regex, enabling method-level access control.

yaml
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
  name: allow-grpc-method
spec:
  endpointSelector:
    matchLabels:
      app: grpc-server
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: grpc-client
    toPorts:
    - ports:
      - port: "50051"
        protocol: TCP
      rules:
        http:
        - method: "POST"
          path: "/helloworld.Greeter/SayHello"

When to Use L7 Policies

ScenarioL7 Policy
API gateway restrictions✅ Yes
gRPC method-level access✅ Yes
Kafka topic restrictions✅ Yes
Simple L3/L4 isolation❌ Use native NetworkPolicy
High-throughput traffic⚠️ L7 has performance cost

Performance note: Benchmarks show eBPF-based Cilium maintains 8.9K Mbps under complex L3/L4 policies, but drops to 94 Mbps with L7 processing. Use L7 policies selectively.


11. Ingress Controllers

An Ingress Controller implements Ingress resources — HTTP/HTTPS routing into the cluster.

Why Ingress Controllers

Without IngressWith Ingress
One LoadBalancer per app (expensive)One external IP, many routes
No path-based routingPath and host-based routing
No TLS terminationCentralized TLS

Ingress Controller Comparison

ControllerPerformanceAuto TLSgRPCTCP/UDP
NGINX Ingress~20K RPScert-manager✅✅
Traefik~19K RPSBuilt-in✅✅
HAProxy Ingress~100K+ RPScert-manager✅✅
Envoy~18.5K RPScert-manager✅✅

HAProxy Ingress is the performance leader, documented at over 100K requests/second per replica with tuning.

NGINX Ingress (Most Popular)

yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - app.example.com
    secretName: tls-secret
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: web
            port:
              number: 80

Traefik (Built-in TLS)

Traefik has built-in Let's Encrypt support, eliminating the need for cert-manager.

yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: web
spec:
  entryPoints:
  - websecure
  routes:
  - match: Host(`app.example.com`)
    kind: Rule
    services:
    - name: web
      port: 80
  tls:
    certResolver: letsencrypt

HAProxy Ingress (Performance Leader)

HAProxy is the performance leader for TCP/UDP load balancing scenarios.

Ingress Class

yaml
spec:
  ingressClassName: nginx

If multiple Ingress controllers exist, ingressClassName selects which one handles the Ingress.

Common Ingress Annotations

AnnotationPurpose
nginx.ingress.kubernetes.io/rewrite-targetRewrite path
nginx.ingress.kubernetes.io/ssl-redirectForce HTTPS
nginx.ingress.kubernetes.io/proxy-body-sizeMax upload
nginx.ingress.kubernetes.io/rate-limitRate limiting
cert-manager.io/cluster-issuerAuto TLS

12. Gateway API

The Gateway API is the official successor to Ingress.

Why Gateway API

Ingress limitations:

  1. Annotation overload — Advanced features require controller-specific annotations that are not portable.
  2. No role separation — The same resource defines infrastructure and application routing.
  3. Limited protocol support — Only HTTP/HTTPS. No TCP, UDP, or gRPC-native routing.
  4. No header-based routing — Cannot route based on headers without annotations.
  5. No traffic splitting — Canary deployments require non-standard annotations.

Gateway API Resources

ResourceOwnerPurpose
GatewayClassInfrastructureDefines the controller
GatewayInfrastructureListener configuration
HTTPRouteApplicationHTTP routing rules
GRPCRouteApplicationgRPC routing
TLSRouteApplicationTLS passthrough
ReferenceGrantApplicationCross-namespace refs

Gateway API Example

Infrastructure team creates the Gateway:

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: main-gateway
  namespace: gateway-system
spec:
  gatewayClassName: istio
  listeners:
  - name: http
    protocol: HTTP
    port: 80
    allowedRoutes:
      namespaces:
        from: All
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - name: wildcard-tls

Application team creates routes:

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: app-routes
  namespace: default
spec:
  parentRefs:
  - name: main-gateway
    namespace: gateway-system
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /api
    backendRefs:
    - name: api-service
      port: 80

Gateway API Status (2026)

As of 2026, core Gateway API resources — GatewayClass, Gateway, HTTPRoute, GRPCRoute, TLSRoute, and ReferenceGrant — have reached GA (General Availability) and are production-ready. Some route types (TCPRoute, UDPRoute) are still experimental.


13. Ingress vs Gateway API

The Retirement of Ingress NGINX

Ingress NGINX maintenance ends in March 2026. This gives infrastructure teams a deadline and an opportunity to re-evaluate their ingress strategy.

Comparison Table

AspectIngressGateway API
StatusStable (maintenance mode)GA (recommended)
Role separation❌ No✅ Yes
Protocol supportHTTP/HTTPSHTTP, HTTPS, gRPC, TCP, UDP
Header routingAnnotations only✅ Native
Traffic splittingAnnotations only✅ Native
Cross-namespaceLimited✅ ReferenceGrant
PortabilityController-specific✅ Standard

Migration Guide

Step 1: Deploy a Gateway API controller

Options: Istio, Cilium, Envoy Gateway, NGINX Gateway Fabric, Kong, Traefik.

Step 2: Create GatewayClass and Gateway

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: my-gateway-class
spec:
  controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: my-gateway
spec:
  gatewayClassName: my-gateway-class
  listeners:
  - name: http
    protocol: HTTP
    port: 80

Step 3: Create HTTPRoutes (migrate from Ingress)

Step 4: Test, then remove Ingress resources

Migration Strategy

PhaseAction
1. PilotDeploy Gateway API for one service
2. ValidateTest routing, TLS, observability
3. ExpandMigrate more services
4. RetireRemove Ingress resources

Gateway API is recommended over Ingress for new clusters as of 2026.


14. DNS in Kubernetes

The ndots:5 Problem

Every Pod gets:

text
options ndots:5

Impact: Names with fewer than 5 dots trigger search-domain expansion.

For api.stripe.com:

4 queries for 1 logical lookup.

Fixes

Option 1: Use trailing dots

bash
curl http://api.stripe.com.

The trailing dot means "absolute name" — no search domain expansion.

Option 2: Lower ndots

yaml
spec:
  dnsConfig:
    options:
    - name: ndots
      value: "2"

Now api.stripe.com (2 dots) is treated as absolute.

The 5-Second DNS Timeout

Problem: Parallel A and AAAA UDP queries from the same socket hit the conntrack race condition in the Linux kernel. One packet is dropped. The resolver waits for its 5-second timeout.

Solution: NodeLocal DNSCache.

NodeLocal DNSCache improves cluster DNS performance and resolves the DNAT conntrack contention issue by running a DaemonSet-based DNS caching proxy on cluster nodes.

How it works:

StepWhat Happens
1Pod queries 169.254.20.10 (local link)
2NodeLocal DNSCache receives UDP
3Cache hit → answer locally (sub-ms)
4Cache miss → forward over TCP to CoreDNS
5TCP conntrack entries are short-lived

Result: Eliminates the 5-second timeout.

CoreDNS Metrics to Monitor

MetricWhat It Shows
coredns_dns_requests_totalTotal queries
coredns_dns_responses_totalResponses by rcode
coredns_cache_hits_totalCache hits
coredns_forward_requests_totalUpstream queries
coredns_dns_request_duration_secondsQuery latency

15. Headless Services

A Headless Service (clusterIP: None) returns Pod IPs directly instead of a ClusterIP.

How Headless Works

AspectNormal ServiceHeadless Service
ClusterIPVirtual IPNone
DNS returnsClusterIPAll Pod IPs
Load balancingkube-proxyClient-side
Use caseStatelessStatefulSets

Headless Service Example

yaml
apiVersion: v1
kind: Service
metadata:
  name: db-headless
spec:
  clusterIP: None
  selector:
    app: postgres
  ports:
  - port: 5432

DNS for Headless

text
db-headless.default.svc.cluster.local → 10.244.1.5, 10.244.2.8, 10.244.3.2

Each Pod also gets its own DNS:

text
postgres-0.db-headless.default.svc.cluster.local
postgres-1.db-headless.default.svc.cluster.local
postgres-2.db-headless.default.svc.cluster.local

Use Cases

Use CaseWhy Headless
StatefulSetsStable identity per Pod
DatabasesClients connect to specific replicas
Message queuesBrokers need stable IDs
Peer discoveryPods find each other directly

16. Multi-Cluster Networking

Cluster Mesh (Cilium)

Cilium's Cluster Mesh connects multiple Kubernetes clusters with:

Submariner

Submariner connects clusters across clouds and on-premises. It uses a gateway node in each cluster to establish tunnels.

Multi-Cluster Service Discovery

ApproachTool
Cluster MeshCilium
SubmarinerOpen source
Service MirroringAdmiralty
DNS-basedCoreDNS federation

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