StackPractices
advanced By Mathias Paulenko

Complete Guide to Kubernetes Networking

Understand how Kubernetes networking really works: flat pod network, Service types, Ingress, NetworkPolicies, CNI plugins, DNS, and service mesh.

Introduction

Your pods are Running, the deployment looks healthy, and yet calls time out. Nine times out of ten the problem isn’t the app — it’s the network layer nobody drew on a whiteboard before going to production.

Kubernetes networking rests on three rules defined by the official model:

  1. Every pod gets its own IP address.
  2. Pods can communicate with all other pods on any node without NAT.
  3. Agents on a node (kubelet, system daemons) can communicate with all pods on that node.

Everything else — Services, Ingress, NetworkPolicies, DNS, service meshes — is machinery built on top of that flat pod network. This guide walks through each layer with the YAML you’ll actually deploy, the trade-offs that bite in production, and the commands to run when things break. If you’re new to the platform, Kubernetes Basics for Application Developers covers the ground floor first.

How Traffic Flows Through the Cluster

The pod network is a flat address space: a pod on node A can open a TCP connection to a pod on node B using the pod IP directly. The CNI plugin assigned to the cluster is what makes that true — it programs the overlay, routing, or cloud-native integration that carries packets between nodes.

Services sit on top of the pod network, but here’s the part that surprises people: a Service has no process and no IP stack of its own. Its ClusterIP is a virtual IP that exists only as rules in the kernel of each node. kube-proxy programs those rules, in one of three modes:

  • iptables (default): the kernel rewrites packets with DNAT to a randomly selected endpoint. Cheap, reliable, but rule evaluation is O(n) — painful past a few thousand Services.
  • IPVS: hash-table lookups with real load-balancing algorithms (round robin, least connection). Worth enabling on large clusters.
  • nftables: GA since Kubernetes 1.31. Faster rule updates and better scalability than iptables on modern kernels.

The list of healthy backend pods behind a Service is maintained by EndpointSlices, which track Ready endpoints only — a pod that fails its readiness probe drops out of rotation without being deleted.

A packet from an external client to a pod takes this path:

flowchart diagram: client([External client

Internal traffic is simpler: a pod resolves api-service.production.svc.cluster.local through CoreDNS, gets the ClusterIP, and kube-proxy’s DNAT rules on the local node pick an endpoint. The VIP is never “dialed” — it’s translated before the packet leaves the node.

Service Types

ClusterIP

ClusterIP is the default. It allocates a stable virtual IP reachable only from inside the cluster — the right choice for anything that shouldn’t face the internet.

apiVersion: v1
kind: Service
metadata:
  name: api-service
  namespace: production
  labels:
    app: api
spec:
  type: ClusterIP
  selector:
    app: api
  ports:
    - name: http
      port: 80
      targetPort: 8000
      protocol: TCP
    - name: metrics
      port: 9090
      targetPort: 9090
      protocol: TCP

port is what the VIP listens on; targetPort is the port on the pod. Named ports (name: http) are worth the extra line — they let Deployments change container ports without breaking the Service, and they’re required for Istio’s protocol detection.

NodePort

NodePort exposes the Service on a static port (30000–32767) on every node’s IP. It’s really a ClusterIP plus a node-level rule, so all ClusterIP traffic still works.

apiVersion: v1
kind: Service
metadata:
  name: api-nodeport
spec:
  type: NodePort
  selector:
    app: api
  ports:
    - port: 80
      targetPort: 8000
      nodePort: 30080  # Optional: K8s assigns one if omitted

Use it for development clusters, or when an external load balancer (HAProxy, a hardware LB, a cloud LB outside the Service integration) routes to node IPs. In production, letting random clients hit NodePorts directly is a smell — there’s no TLS, no ACL, and the port range is guessable.

LoadBalancer

type: LoadBalancer asks the cloud provider to provision a real load balancer pointing at your nodes. On bare metal you need a controller like MetalLB to fill the role.

apiVersion: v1
kind: Service
metadata:
  name: api-lb
  annotations:
    # AWS-specific annotations
    service.beta.kubernetes.io/aws-load-balancer-type: nlb
    service.beta.kubernetes.io/aws-load-balancer-internal: "false"
    service.beta.kubernetes.io/aws-load-balancer-ssl-cert: arn:aws:acm:us-east-1:123:certificate/abc
    service.beta.kubernetes.io/aws-load-balancer-ssl-ports: "443"
spec:
  type: LoadBalancer
  selector:
    app: api
  ports:
    - name: http
      port: 80
      targetPort: 8000
    - name: https
      port: 443
      targetPort: 8000
  externalTrafficPolicy: Local  # Preserve client source IP

externalTrafficPolicy is the knob that matters here:

  • Cluster (default): the receiving node forwards to a pod anywhere, adding a hop and SNAT — the backend sees the node IP, not the client.
  • Local: packets only reach pods on the receiving node, preserving the client IP. The catch: nodes without a local endpoint advertise themselves out of the LB health check, so traffic only lands where endpoints run.

LoadBalancer annotations are provider-specific — the AWS service.beta.kubernetes.io/* family above does nothing on GCP or Azure, which have their own (cloud.google.com/*, service.beta.kubernetes.io/azure-*). For HTTP workloads, you’ll usually prefer Ingress and let one LB front many Services instead of paying per-Service.

Headless Service

Set clusterIP: None and the Service stops doing load balancing entirely. DNS then returns the individual pod IPs instead of one VIP — which is exactly what StatefulSets need for stable pod identity (postgres-0.database.production.svc.cluster.local).

apiVersion: v1
kind: Service
metadata:
  name: database-headless
spec:
  clusterIP: None  # Headless
  selector:
    app: postgres
  ports:
    - port: 5432
      targetPort: 5432

Also useful when the client does its own load balancing (gRPC clients, for example) and a VIP would pin all traffic to a single connection.

Choosing a Service Type

NeedTypeNotes
Internal pod-to-pod trafficClusterIPDefault; never skip it for external exposure
Quick external access on dev/homelabNodePortNo TLS, no ACL — not for production
Non-HTTP external traffic, cloudLoadBalancerOne LB per Service — cost adds up
Many HTTP hosts/paths behind one IPIngress (on ClusterIP)TLS, routing, rate limiting in one place
Stable pod identity (StatefulSet)clusterIP: NoneClients get pod IPs directly
Map an external hostname into the clusterExternalNameReturns a CNAME — no proxying at all

One rule of thumb covers most cases: everything starts as ClusterIP, HTTP exposure goes through Ingress, and LoadBalancer is reserved for TCP/UDP services Ingress can’t carry.

Ingress

Ingress is an L7 router for HTTP and HTTPS: name-based virtual hosting, path routing, and TLS termination at a single entry point. The Ingress resource itself does nothing until a controller (ingress-nginx, Traefik, HAProxy) watches and programs it — and the annotations are controller-specific, so a manifest tuned for ingress-nginx won’t carry over verbatim to Traefik.

# Ingress with NGINX ingress controller
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-ingress
  namespace: production
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rate-limit: "100"
    nginx.ingress.kubernetes.io/rate-limit-window: "1m"
    nginx.ingress.kubernetes.io/proxy-body-size: "10m"
    nginx.ingress.kubernetes.io/configuration-snippet: |
      more_set_headers "X-Content-Type-Options: nosniff";
      more_set_headers "X-Frame-Options: DENY";
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - api.stackpractices.com
        - www.stackpractices.com
      secretName: tls-secret
  rules:
    - host: api.stackpractices.com
      http:
        paths:
          - path: /v1
            pathType: Prefix
            backend:
              service:
                name: api-v1-service
                port:
                  number: 80
          - path: /v2
            pathType: Prefix
            backend:
              service:
                name: api-v2-service
                port:
                  number: 80
    - host: www.stackpractices.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: frontend-service
                port:
                  number: 80

pathType trips people up: Prefix matches /v1 and /v1anything (/v1foo matches too — use /v1/ if that’s not intended), while Exact matches the literal string only.

Ingress with Cert-Manager (Automatic TLS)

cert-manager watches Ingresses, solves ACME challenges, and stores the issued certificates in Secrets — no manual renewals:

# ClusterIssuer for Let's Encrypt
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: admin@stackpractices.com
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
      - http01:
          ingress:
            class: nginx

---
# Ingress with automatic certificate
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-ingress-tls
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - api.stackpractices.com
      secretName: api-tls-cert  # cert-manager creates this
  rules:
    - host: api.stackpractices.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: api-service
                port:
                  number: 80

The successor to Ingress is the Gateway API (GatewayClass, Gateway, HTTPRoute), which separates infra ownership from app routing and ships with most modern controllers — Cilium, Istio, Envoy Gateway, Traefik, NGINX Gateway Fabric. Ingress isn’t deprecated, but new designs should evaluate Gateway first. For the full controller comparison, TLS modes, and production hardening, see the dedicated Complete Guide to Kubernetes Ingress and the Gateway Routing Pattern.

NetworkPolicies

By default every pod can talk to every other pod — a flat, open network is great until one compromised workload starts scanning the cluster. NetworkPolicies are the firewall layer: once a policy selects a pod, that pod becomes isolated and only explicitly allowed traffic flows.

Two details to internalize:

  • Policies are additive. If three policies select the same pod, the union of their rules applies — you can’t write a “deny” that beats an “allow” from another policy. Default-deny comes first precisely so the allowlist stays meaningful.
  • The CNI enforces them. Flannel doesn’t implement NetworkPolicy at all; Calico and Cilium do (Cilium adds L7 rules for HTTP, Kafka, gRPC via its own CRDs). Test enforcement before trusting a deny rule.

Default Deny All

# Default deny all ingress traffic in namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: production
spec:
  podSelector: {}  # Selects all pods in namespace
  policyTypes:
    - Ingress

---
# Default deny all egress traffic in namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-egress
  namespace: production
spec:
  podSelector: {}
  policyTypes:
    - Egress

Careful with the egress deny: it also blocks DNS. Every deny-all-egress namespace needs a companion rule allowing UDP and TCP port 53 to kube-system, or nslookup failures will be your first alert. The manifests below include it.

Allow Specific Traffic

# Allow API to receive traffic from Ingress controller only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow-ingress-controller
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: ingress-nginx
          podSelector:
            matchLabels:
              app.kubernetes.io/name: ingress-nginx
      ports:
        - protocol: TCP
          port: 8000

---
# Allow API to connect to database only
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-allow-db-egress
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Egress
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: postgres
      ports:
        - protocol: TCP
          port: 5432
    # Allow DNS resolution
    - to:
        - namespaceSelector:
            matchLabels:
              name: kube-system
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

namespaceSelector matches labels on the namespace, not the pods — label your namespaces deliberately (kubernetes.io/metadata.name is set automatically on every namespace since 1.21 and is the safest selector). An empty podSelector: {} inside a from:/to: block means “all pods in the policy’s own namespace”.

Micro-segmentation with NetworkPolicies

The production pattern is layered: default-deny both directions, then narrow allow rules per workload.

# Full micro-segmentation policy set
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: frontend-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: frontend
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              name: ingress-nginx
      ports:
        - protocol: TCP
          port: 3000
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: api
      ports:
        - protocol: TCP
          port: 8000
    - to:
        - namespaceSelector: {}
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: api-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: api
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: frontend
      ports:
        - protocol: TCP
          port: 8000
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: postgres
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - podSelector:
            matchLabels:
              app: redis
      ports:
        - protocol: TCP
          port: 6379
    - to:
        - namespaceSelector: {}
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53

When policy evaluation gets complicated, render the effective rules with kubectl describe networkpolicy or a visualizer like Cilium’s Hubble — guessing which selector matched is how port 443 ends up open to the world.

CNI Plugins

The CNI plugin builds the pod network itself, so the choice locks in dataplane performance, policy enforcement, and observability before you deploy a single app.

PluginDataplaneNetworkPolicyBest for
CiliumeBPF, no kube-proxy neededFull + L7 (HTTP, Kafka, gRPC) via CiliumNetworkPolicyModern clusters wanting performance, built-in mesh capabilities, and Hubble observability
CalicoBGP or overlay, eBPF optionFull K8s NetworkPolicy + Calico GlobalNetworkPolicyProduction clusters that need battle-tested policy and cluster-wide rules
FlannelVXLAN overlayNone (pair with Calico for policy)Simple clusters, learning, homelab
AWS VPC CNINative VPC — pods get real VPC IPsVia policy engine add-on (Calico-compatible)EKS; pods addressable directly from the VPC

Two operational details worth knowing:

  • eBPF dataplanes change the debugging model. With Cilium there’s no iptables to inspect — cilium monitor and Hubble become the packet-path tools. Teams used to iptables -L need the new toolchain.
  • VPC-native CNIs burn through IP space. AWS VPC CNI assigns real subnet IPs to pods; without prefix delegation (enabled by default in recent versions) a /24 fills fast. Plan subnet sizing before the cluster, not after.

DNS in Kubernetes

CoreDNS runs in kube-system and answers for the whole cluster. Services get A records, headless Services return pod IPs, and everything else falls through to upstream resolvers.

RecordFormatResolves to
Service (normal)<service>.<namespace>.svc.cluster.localClusterIP VIP
Service (short)<service> or <service>.<namespace>Same — via search domains
Pod (headless)<pod-name>.<service>.<namespace>.svc.cluster.localPod IP (StatefulSet identity)
Pod (individual)<pod-ip>.<namespace>.pod.cluster.localPod IP, rarely needed

The ndots: 5 default is a quiet latency source: any name with fewer than five dots is tried against every search domain (production.svc.cluster.local, svc.cluster.local, cluster.local, then the node’s) before the literal name is queried. A pod calling api.example.com issues up to four failed lookups first. Fix it with a trailing dot (api.example.com. → FQDN, skips search expansion) or a custom dnsConfig:

# Custom DNS configuration for a pod
apiVersion: v1
kind: Pod
metadata:
  name: custom-dns-pod
spec:
  dnsPolicy: None
  dnsConfig:
    nameservers:
      - 8.8.8.8
      - 1.1.1.1
    searches:
      - stackpractices.com
      - production.svc.cluster.local
    options:
      - name: ndots
        value: "5"
  containers:
    - name: app
      image: myapp:latest

dnsPolicy: None disables cluster DNS entirely for the pod — only do this for workloads that genuinely must bypass it. At scale, cluster-proportional-autoscaler grows CoreDNS replicas with the node count, and NodeLocal DNSCache kills most latency and conntrack issues on big clusters.

Service Mesh

A mesh adds transparent L7 behavior — mTLS, retries, traffic splitting, telemetry — without changing app code. The price is an extra data plane to deploy, version, and debug.

Istio mTLS

# Enable strict mTLS for entire namespace
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: default
  namespace: production
spec:
  mtls:
    mode: STRICT

---
# Enable mTLS for specific service
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: api-mtls
  namespace: production
spec:
  selector:
    matchLabels:
      app: api
  mtls:
    mode: STRICT
  portLevelMtls:
    9090:
      mode: PERMISSIVE  # Allow plaintext for metrics endpoint

PERMISSIVE on the metrics port is the standard trick for letting Prometheus scrape without sidecar-managed certs during migration.

Istio Traffic Management

# Canary deployment with Istio
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
  name: api-virtualservice
  namespace: production
spec:
  hosts:
    - api.stackpractices.com
  gateways:
    - istio-system/ingress-gateway
  http:
    - match:
        - headers:
            x-canary:
              exact: "true"
      route:
        - destination:
            host: api-service
            subset: v2
            port:
              number: 80
    - route:
        - destination:
            host: api-service
            subset: v1
            port:
              number: 80
          weight: 90
        - destination:
            host: api-service
            subset: v2
            port:
              number: 80
          weight: 10

---
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
  name: api-destination
  namespace: production
spec:
  host: api-service
  subsets:
    - name: v1
      labels:
        version: v1
    - name: v2
      labels:
        version: v2

The header-match route ships canary traffic to testers before the weighted split touches real users — a pattern worth copying. If sidecars are a concern, Istio’s ambient mode (stable since 1.24) gives you mTLS and L4 telemetry without injecting proxies, and Linkerd remains the lighter-weight alternative for mTLS + golden metrics without the Istio API surface.

Best Practices

  • Every deny-all-egress needs a DNS rule. UDP and TCP port 53 to kube-system — TCP matters because DNS falls back to TCP for large responses and truncation.
  • Name your Service ports. name: http, name: grpc let Istio detect protocols; unnamed ports degrade to plain TCP and lose L7 routing.
  • Default to ClusterIP + Ingress for HTTP. One cloud LB, one TLS stack, dozens of services. Reserve LoadBalancer for non-HTTP traffic.
  • Set externalTrafficPolicy: Local when the client IP matters (rate limiting, geo rules, audit logs) — and accept that traffic only lands on nodes running endpoints.
  • Label namespaces, not just pods. kubernetes.io/metadata.name exists on every namespace; policies built on it survive namespace recreation.
  • Use headless Services for StatefulSets and gRPC. Pod-level DNS and client-side balancing both need real pod IPs, not a VIP.
  • Reserve a nodePort range mentally. Static assignments collide on shared clusters; letting Kubernetes assign avoids 30080-style conventions colliding between teams.

Troubleshooting

Work the layers in order — most “networking is broken” reports resolve in the first two steps:

# 1. Does the Service have endpoints? (Empty = selector or readiness issue)
kubectl get endpoints api-service -n production
kubectl describe svc api-service -n production

# 2. Does DNS resolve from inside a pod?
kubectl exec -it <pod> -- nslookup api-service.production
kubectl get svc -n kube-system kube-dns
kubectl logs -n kube-system <dns-pod> --tail=50

# 3. Can a pod reach the Service directly?
kubectl exec -it <pod> -- curl -v http://api-service.production:80
kubectl debug -it <pod> --image=nicolaka/netshoot  # ephemeral debug container

# 4. Is a NetworkPolicy dropping traffic?
kubectl get networkpolicy -n production
kubectl describe networkpolicy <policy-name> -n production

# 5. Is the CNI healthy?
kubectl get pods -n kube-system | grep -E "calico|cilium|flannel"
kubectl logs -n kube-system <cni-pod>

# 6. Is Ingress programmed?
kubectl get ingress -n production
kubectl describe ingress <ingress-name> -n production
kubectl logs -n ingress-nginx <controller-pod>

# 7. Packet-level: trace path and watch traffic
kubectl exec -it <pod> -- traceroute api-service.production
kubectl exec -it <pod> -- tcpdump -i any port 80 -nn

# 8. Conntrack exhaustion (random connection resets under load)
kubectl exec -it <node-pod> -- cat /proc/net/nf_conntrack | wc -l

Step 1 catches the most common case by far: endpoints is empty because the Service selector doesn’t match pod labels or pods aren’t Ready. Step 8 is the sneaky one — a full conntrack table produces intermittent resets that look exactly like app flakiness.

See Also

Frequently Asked Questions

What is the difference between ClusterIP and NodePort?

ClusterIP gives the Service a virtual IP reachable only inside the cluster; NodePort additionally opens a static port (30000–32767) on every node's IP. Use ClusterIP for all internal traffic. NodePort is fine for dev clusters or as a target for an external load balancer, but production HTTP traffic should go through LoadBalancer or Ingress.

When should I use Ingress vs a LoadBalancer Service?

Use Ingress for HTTP/HTTPS: many hosts and paths behind one IP, TLS termination, and controller extras like rate limiting and auth. Use type: LoadBalancer for non-HTTP protocols (TCP/UDP) or when a single service needs its own dedicated cloud LB. Ingress is cheaper — one load balancer fronts the whole set.

How do NetworkPolicies work?

They're an allowlist firewall for pods. Everything is open until a policy selects a pod; from that moment, only explicitly permitted ingress and egress flows. Policies landing on the same pod union their rules — there's no precedence or explicit deny. Enforcement is the CNI's job, so verify your plugin supports it (Calico, Cilium; Flannel doesn't).

Which CNI plugin should I choose?

Cilium for eBPF performance, L7 policies, and built-in observability. Calico for proven NetworkPolicy enforcement and BGP routing. Flannel only for simple clusters where you won't need policies. On EKS, the AWS VPC CNI is the default — add its policy engine or Calico for enforcement. On GKE, the default dataplane covers most cases.

How does DNS resolution work in Kubernetes?

CoreDNS in kube-system serves cluster records: Services get <service>.<namespace>.svc.cluster.local, and headless Services resolve to individual pod IPs. With the default ndots: 5, names with fewer than five dots are expanded against the search domains first — that's why api.example.com can take four failed lookups before resolving, and why a trailing dot (FQDN) fixes it.

Should I use a service mesh?

Adopt one when you need mTLS everywhere, canary/blue-green traffic splits, retries with budgets, or fleet-wide telemetry — Istio or Linkerd. Skip it while native resources (Services, Ingress, NetworkPolicies) cover your needs; the operational overhead is real. If you do adopt, start with a single namespace in PERMISSIVE mode before flipping STRICT.

Is Ingress being replaced by Gateway API?

Ingress is stable and supported, but Gateway API (Gateway, HTTPRoute, GRPCRoute) is where the ecosystem is investing: better role separation, typed routes, and first-class support in Cilium, Istio, and Envoy Gateway. New deployments should evaluate Gateway API; existing Ingress setups don't need a rushed migration.