Lesson 20 of 24Kubernetes
Services, Gateway API and Network Policies
Follow a request through Kubernetes: Service virtual IPs, EndpointSlices, cluster DNS, Gateway API routing, TLS and default-deny network policies.
The web frontend starts returning 502s right after a harmless-looking deploy of api. The pods are Running and 1/1 ready, the logs are clean, and yet nothing reaches them. Twenty minutes later someone spots it: the new manifest renamed the pod label from app: api to app.kubernetes.io/name: api, and the Service still selects the old one. Kubernetes networking is mostly invisible when it works, and this lesson makes it visible: what a Service actually is on the wire, how names resolve, how outside traffic gets in now that the most popular Ingress controller has been retired, and how to lock pod-to-pod traffic down.
What a Service really is
In From Containers to Kubernetes a Service was "a stable name and virtual IP". Here is what sits behind that sentence.
A ClusterIP Service gets a virtual IP from a reserved range, for example 10.96.12.4. No process listens on that IP. No network interface owns it. Instead, three pieces cooperate:
- The EndpointSlice controller watches pods. For every pod that matches the Service's selector, it writes the pod's IP, port and readiness into EndpointSlice objects (slices of up to 100 endpoints each, so huge Services do not produce one giant object).
- kube-proxy runs on every node and watches Services and EndpointSlices. It programs the node's kernel, using iptables or nftables rules, so that a packet to
10.96.12.4:80is rewritten (DNAT) to one ready pod IP, such as10.244.2.7:8000. - The packet then travels over the pod network, which the CNI plugin (Calico, Cilium, the cloud's own VPC CNI) provides.
So a Service is not a proxy in the path. It is a rule installed on every node, and the load balancing decision happens in the kernel of the node the client pod runs on.
The controller matches the Service's selector against pod labels. No label match, no endpoints, no matter how healthy the pods are.
On Linux, kube-proxy's default mode is still iptables, with nftables stable and expected to become the default in a future release; the older ipvs mode is being phased out. Many clusters replace kube-proxy entirely with an eBPF dataplane such as Cilium, which does the same translation with eBPF programs and scales better with thousands of Services. Check which one your cluster runs before debugging at that level.
One consequence surprises people in interviews and in production: the choice of pod happens per connection, not per request. HTTP/1.1 keep-alive clients and especially gRPC (one long-lived HTTP/2 connection) can pin all their traffic to one pod while the others sit idle. The fixes are client-side load balancing (gRPC with a headless Service), periodically recycling connections, or a mesh or proxy that balances per request.
Service types
| Type | What you get | Use it for |
|---|---|---|
| ClusterIP (default) | A virtual IP reachable only inside the cluster | Almost every internal Service |
| NodePort | ClusterIP plus a port (30000 to 32767 by default) opened on every node | Rarely directly; external load balancers sometimes target it |
| LoadBalancer | NodePort plus a cloud load balancer provisioned for this Service | Non-HTTP traffic (TCP, UDP), or a single entry point. One cloud LB per Service adds up fast in cost |
Headless (clusterIP: None) | No virtual IP; DNS returns the pod IPs directly | StatefulSets (db-0.db), client-side load balancing |
| ExternalName | A DNS CNAME to an outside host | Giving an external database an in-cluster name |
For HTTP, you normally have one load balancer in front of a Gateway (or Ingress) controller, which routes by host and path to many ClusterIP Services. That is the main reason Gateway and Ingress exist.
Match each need to the Service type.
Cluster DNS and the ndots trap
CoreDNS gives every Service a name. From a pod in namespace shop, all of these reach the api Service in shop:
api(same namespace only)api.shop(any namespace)api.shop.svc.cluster.local(the fully qualified name;cluster.localis the default cluster domain)
Short names work because the pod's /etc/resolv.conf has a search list (shop.svc.cluster.local svc.cluster.local cluster.local, plus whatever the node adds) and options ndots:5. The rule: if a name has fewer than 5 dots, the resolver tries it with each search suffix first, and only then as written. That is great for api, and wasteful for external names.
Press Run (⌘ Enter) to see what happens.api.stripe.com has 2 dots, so it goes through three failing in-cluster lookups before the real one, and resolvers often send A and AAAA queries for each. On a busy service that is a lot of extra DNS load and latency, and it is a classic cause of CoreDNS saturation and timeouts. Fixes: write external names with a trailing dot (api.stripe.com.), lower ndots in the pod's dnsConfig.options, or add NodeLocal DNSCache to cache on each node.
What does this print?
SEARCH = ["shop.svc.cluster.local", "svc.cluster.local", "cluster.local"]
name = "postgres.payments.svc"
found = "postgres.payments.svc.cluster.local"
tries = [f"{name}.{d}" for d in SEARCH] + [name]
print(tries.index(found) + 1)Getting traffic in: Ingress and Gateway API
For years, HTTP traffic entered through an Ingress resource plus an Ingress controller, and the most common controller by far was the community ingress-nginx. Two facts matter now:
- The ingress-nginx controller was retired in March 2026. It gets no more releases, bug fixes or security patches. Existing installs keep running, but an internet-facing proxy without security fixes is a liability, so teams are migrating. Do not confuse it with F5's separate NGINX Ingress Controller, which is a different project.
- The Ingress API itself is not removed. It is feature-frozen. It still works with the controllers that support it, but new features go into Gateway API.
Ingress had a design problem: the spec covers only host and path routing, so everything else (rewrites, timeouts, canaries, header matching) lived in controller-specific annotations. Configs were not portable, and one object mixed platform concerns with app concerns.
Gateway API splits the job into roles:
- GatewayClass (cluster admin or cloud provider): which controller implements gateways, such as Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, or a cloud provider's own controller.
- Gateway (platform team): the actual entry point: listeners, ports, hostnames, TLS certificates, and which namespaces may attach routes.
- HTTPRoute (app team, in their own namespace): host and path matches, header matches, and weighted backends. Also
GRPCRouteand others.
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: public
namespace: infra
spec:
gatewayClassName: eg # whatever your controller installs
listeners:
- name: https
protocol: HTTPS
port: 443
hostname: "*.shop.com"
tls:
mode: Terminate
certificateRefs:
- name: shop-com-tls # a Secret, often filled by cert-manager
allowedRoutes:
namespaces:
from: Selector
selector:
matchLabels:
shared-gateway-access: "true"apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: api
namespace: shop
spec:
parentRefs:
- name: public
namespace: infra
hostnames: ["api.shop.com"]
rules:
- matches:
- path: { type: PathPrefix, value: / }
backendRefs:
- name: api-v1
port: 80
weight: 90
- name: api-v2 # canary: about 10% of requests
port: 80
weight: 10The platform team owns the Gateway and its certificate; the app team ships its HTTPRoute alongside its Deployment and can run a canary by changing two numbers. Weights are proportional, not percentages, so 9 and 1 means the same as 90 and 10. For migrations, the ingress2gateway tool converts existing Ingress objects, but read the output: annotation-driven behaviours (regex paths, rewrites) do not always map one to one.
TLS
Inside the cluster, cert-manager is the standard way to get certificates. You create an Issuer or ClusterIssuer (for example Let's Encrypt with an ACME HTTP-01 or DNS-01 challenge) and a Certificate; cert-manager obtains the certificate, stores it in a Secret and renews it before it expires.
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: shop-com
namespace: infra
spec:
secretName: shop-com-tls
dnsNames: ["api.shop.com", "www.shop.com"]
issuerRef:
kind: ClusterIssuer
name: letsencrypt-prodOn AWS, a common alternative is to terminate TLS at an Application Load Balancer created by the AWS Load Balancer Controller, with the certificate in ACM, so no private key ever lives in the cluster. Check the controller's docs for which Ingress and Gateway API features your version supports.
Order the hops of a request to https://api.shop.com/orders through Gateway API.
- Tap the steps below in the right order.
NetworkPolicy: default deny, then allow
By default, every pod can reach every other pod in the cluster, across namespaces. A compromised pod in a low-value service can then talk straight to your payments database. A NetworkPolicy selects pods and lists what may reach them (ingress) or what they may reach (egress).
The rules that trip people up:
- A pod is only isolated in a direction once some policy selects it for that direction. Policies are additive: the allowed traffic is the union of all policies that apply. There is no "deny" rule and no ordering.
- Both ends must agree: the source's egress and the destination's ingress must each allow the connection.
- Policies are enforced by the CNI plugin. Calico and Cilium enforce them; a plain Flannel setup accepts the objects and silently ignores them. Test that a blocked connection actually fails.
- Ports in a policy are the pod's port (8000), not the Service's port (80).
The usual pattern is a default-deny policy per namespace, then explicit allows:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
namespace: shop
spec:
podSelector: {} # every pod in the namespace
policyTypes: ["Ingress"] # no ingress rules listed, so nothing may connect in
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-allow-web
namespace: shop
spec:
podSelector:
matchLabels: { app: api }
policyTypes: ["Ingress"]
ingress:
- from:
- podSelector:
matchLabels: { app: web }
ports:
- protocol: TCP
port: 8000If you also default-deny egress, remember to allow DNS (UDP and TCP 53 to the CoreDNS pods in kube-system), or every pod breaks in a confusing way: connections fail because names never resolve. Do not forget the Gateway either: if its controller runs in infra, api also needs a rule allowing ingress from that namespace.
web can reach api, but the public site through the Gateway returns 503 for API calls. What is the most likely cause?Service mesh, briefly
A service mesh (Istio, Linkerd) adds a proxy layer that gives you mutual TLS between every pair of services, per-request load balancing, retries and timeouts, and uniform metrics, without code changes. Istio's ambient mode does this without a sidecar in every pod, using a per-node proxy for mTLS and optional per-namespace proxies for HTTP features, which cuts most of the resource overhead that gave meshes a bad name. Linkerd is the smaller, simpler option.
A mesh is worth it when you have many services, a security requirement for encrypted and authenticated service-to-service traffic, or a need for consistent traffic policy across teams. For a handful of services it is another distributed system to upgrade and debug. Say that out loud in an interview; it shows judgement.
Debugging a Service that does not answer
Work from the pod outwards. Each step removes one layer.
Step 1: does the name resolve? From a debug pod run nslookup api. NXDOMAIN means a wrong name or namespace.
kubectl get endpointslices -l kubernetes.io/service-name=api -n shopkubectl get svc api -n shop -o yaml # compare spec.selector with the pod labelskubectl get pods -n shop --show-labelskubectl port-forward svc/api 8080:80 -n shop # bypasses DNS and policies: is the app fine?kubectl run tmp -n shop --rm -it --image=nicolaka/netshoot -- bashnetshoot is a popular image with dig, curl, tcpdump and friends; run it in the same namespace and test the exact call the client makes. If port-forward works but the in-cluster call does not, the problem is between pods: DNS, endpoints or policy.
kubectl get endpointslices -l kubernetes.io/service-name=api shows no endpoints, but kubectl get pods shows three healthy, ready api pods. What is the first thing to compare?- ClusterIP
- A virtual IP for a Service, reachable inside the cluster and implemented by rules on every node.
- EndpointSlice
- An object listing the IPs, ports and readiness of the pods behind a Service.
- kube-proxy
- The node agent that turns Services and EndpointSlices into iptables or nftables rules.
- headless Service
- A Service with
clusterIP: None, whose DNS name returns the pod IPs directly. - Gateway API
- The successor to Ingress: GatewayClass, Gateway and HTTPRoute, split by team role.
- ndots
- Resolver option: names with fewer dots than this are tried with search suffixes first.
- NetworkPolicy
- Rules, enforced by the CNI, that limit which pods may connect to or from selected pods.