Ingress and Gateway API: routing, TLS termination, timeouts, and 502/503/504 diagnosis

Ingress is a controller reading rules and configuring a proxy. Where TLS terminates and which timeout applies explains most 502/504 arguments.

Read the briefing
About 11 min to read 9 drills

What to remember

  1. The controller is just a proxy plus a config loop. Nothing magic: read the generated nginx/Envoy config when behaviour surprises you.
  2. Know where TLS terminates. At the load balancer, at the ingress, or end to end at the pod — each has different failure modes and different certs.
  3. Annotations are controller-specific and unversioned. Half of 'ingress does not work' is an annotation for a different controller.
  4. Gateway API replaces Ingress's annotation sprawl with typed resources. Role separation between infra and app teams is the actual motivation.
  5. The ingress timeout must exceed your slowest legitimate request. Otherwise 504s appear for exactly the endpoints that matter most.

The big picture

An Ingress is a routing wish: hosts, paths, backend Services and TLS Secrets. A controller turns it into a running proxy, and that proxy sits in a chain of hops (load balancer, controller, pod) that each have their own timeouts, limits and failure codes. Interviewers use this node to check whether you can read a 502, 503 or 504 as evidence about a specific hop, know that TLS and rewrites live where the API says they do, and can explain how Gateway API splits the same problem across the people who own each part.

The mental model

Picture a request crossing three proxies in a row: the L4 balancer in front of the cluster, the controller pod that holds the rendered routing table, and the application pod. The Ingress or HTTPRoute is only the source text for the middle hop. Every hop has a timeout, a body limit and a keep-alive setting, and the shortest one wins. Each status code names the hop that failed: 503 means the controller found nobody to send to, 502 means it reached a pod and got garbage, 504 means it waited and gave up. Debug by reading the controller's log line first, then the endpoints, then the pod directly.

In depth

An Ingress is a wish; a controller makes it real

An Ingress is a namespaced routing spec: hosts, paths, backend Services, TLS Secrets. Nothing in the control plane acts on it. An ingress controller (ingress-nginx, HAProxy, Traefik, Envoy-based projects, or a cloud controller that programs a provider load balancer) watches Ingresses whose spec.ingressClassName names its IngressClass, renders them into proxy configuration, and reports where it is listening in status.loadBalancer. That status is what kubectl get ingress prints in the ADDRESS column. An empty ADDRESS is the first diagnostic: no controller has adopted the object, usually because the class name is wrong, no class carries ingressclass.kubernetes.io/is-default-class: "true", or the controller is not running.

The controller itself is ordinary workload: a Deployment or DaemonSet in its own namespace, exposed by a type: LoadBalancer Service. Everything from the Services node applies to that Service: externalTrafficPolicy: Local or proxy protocol if you want client IPs, NodePort health checks, and the fact that the balancer in front of it has its own idle timeout. A request path is therefore client, L4 balancer, controller pod, application pod. Most controllers route to pod IPs read from EndpointSlices rather than to the ClusterIP, so they can balance per request, health-check upstreams and support cookie affinity; ingress-nginx's service-upstream annotation switches back to the ClusterIP.

Commands that establish the picture:

kubectl get ingressclass
kubectl get ingress -A                      # ADDRESS empty = not adopted
kubectl describe ingress shop -n shop       # events: sync errors, admission rejections
kubectl -n ingress-nginx logs deploy/ingress-nginx-controller

Keep the separation in mind: the Ingress is intent, the controller is behaviour, and the Service with its EndpointSlices is the truth about backends. When "routing does not work", ask which of the three you are actually looking at, because each has a different fix and a different owner.

Routing rules: host, path, and what wins

A rule matches on host first, then path. A rule without a host catches every request that no host rule claimed. Hosts can be wildcards: *.example.com matches shop.example.com but not example.com or a.b.example.com; a wildcard covers exactly one label. Paths carry a pathType:

  • Exact matches the path literally.
  • Prefix matches element by element on /-separated segments: /api matches /api, /api/ and /api/v1/orders, and does not match /apix or /api-v2. A trailing slash on the rule is ignored, so /foo/ also matches /foo.
  • ImplementationSpecific hands the string to the controller; for ingress-nginx it is where regular expressions live, together with the use-regex annotation.

When several paths match, the longest wins; on a tie, Exact beats Prefix. Requests that match no rule go to spec.defaultBackend or the controller's default backend, which answers 404.

Everything else you might expect from a router is not in the API: rewrites, redirects, rate limits, timeouts, CORS, authentication, canaries. They are controller annotations such as nginx.ingress.kubernetes.io/rewrite-target, and an annotation applies to the whole Ingress object, never to one path. That is why the standard advice is one Ingress per distinct annotation set. Rewrites are also the most common self-inflicted 404: rewrite-target: / rewrites every matched request to /, so /api/v1/orders reaches the backend as /. Keeping a suffix needs a capture group:

metadata:
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  rules:
    - host: shop.example.com
      http:
        paths:
          - path: /api(/|$)(.*)
            pathType: ImplementationSpecific
            backend: { service: { name: api, port: { number: 8080 } } }

Two Ingress objects that claim the same host and path conflict; resolution is controller-specific (ingress-nginx keeps the older one and logs a warning), so the second team's route silently never applies. kubectl describe ingress and the controller log show these collisions; nothing in the API server does.

TLS termination and certificates

TLS ends at the controller. An Ingress's spec.tls entry names a Secret of type kubernetes.io/tls (keys tls.crt and tls.key: the certificate chain and the private key) and lists the hosts it covers. The Secret must live in the Ingress's namespace; the controller looks it up as <namespace>/<secretName>, and a Secret elsewhere does not exist as far as this Ingress is concerned. The controller uses SNI to pick a certificate: the client names the host in the TLS handshake and the controller serves the certificate registered for that host. When none is registered, because the Secret is missing, malformed, or does not cover the host, the controller falls back to its default certificate, which for ingress-nginx is the self-signed "Kubernetes Ingress Controller Fake Certificate". Browsers warn, and the controller log says Error obtaining X.509 certificate with the key it looked for. To see exactly what is being served:

openssl s_client -servername shop.example.com -connect <lb-ip>:443 </dev/null 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates

Once TLS is configured, ingress-nginx redirects plain HTTP to HTTPS with a 308 (ssl-redirect), and a client that speaks plain HTTP to port 443 receives 400 The plain HTTP request was sent to HTTPS port. Traffic from the controller to the pod is plain HTTP by default; re-encrypting is controller-specific (backend-protocol: "HTTPS" in ingress-nginx, BackendTLSPolicy in Gateway API), and TLS passthrough (routing on SNI without terminating) is a separate mode that disables every L7 feature for that host.

cert-manager automates issuance: a cert-manager.io/cluster-issuer annotation on the Ingress creates a Certificate, solves the ACME HTTP-01 challenge through a temporary Ingress path, and writes the Secret into the Ingress's namespace. Alert on expiry (certmanager_certificate_expiration_timestamp_seconds) and on the default certificate being served, because both fail silently until users complain.

Timeouts, keep-alives, and body limits: every hop has its own

A request through an ingress crosses at least three independently configured proxies, and each has its own idea of how long to wait and how much to accept:

hop knobs (ingress-nginx names) typical default
L4 balancer idle timeout provider-specific, often 60 s to a few minutes
controller proxy-connect-timeout 5 s, proxy-read-timeout and proxy-send-timeout 60 s, proxy-body-size 1m, proxy-buffer-size 4k, upstream-keepalive-timeout 60 s ConfigMap-wide, overridable per Ingress by annotation
application server keep-alive idle timeout, request timeout, max body runtime-specific

The shortest timeout wins. A report that takes 90 s behind a 60 s proxy-read-timeout is a 504 every time, and raising the controller timeout only moves the failure to the balancer's idle timeout. Websockets and long polling need proxy-read-timeout and proxy-send-timeout well above the expected idle period, or they drop at exactly the timeout. Anything that legitimately takes longer than tens of seconds should become asynchronous (accept, return 202, poll) rather than stretching every timeout in the chain.

Keep-alive mismatches cause intermittent 502s. The controller keeps idle connections to pods open for upstream-keepalive-timeout. If the application closes idle connections sooner (some runtimes default to 5 s; many frameworks pick 15-30 s), the controller occasionally reuses a connection the application closed a millisecond earlier, and the log says upstream prematurely closed connection while reading response header. The fix is an invariant: application idle timeout greater than the proxy's upstream keep-alive timeout (75 s against 60 s is a common pairing), or disabling upstream keep-alive at a latency cost.

Sizes. A body above proxy-body-size returns 413 before the pod sees it; large uploads need the limit raised per Ingress and often proxy-request-buffering: "off". Large cookies or tokens in headers overflow proxy-buffer-size and surface as 502 upstream sent too big header. Each of these is a per-Ingress annotation, so scope them to the route that needs them rather than raising the cluster-wide default.

Reading 502, 503, 504 and 413 like the controller does

From the controller's point of view each status names a different failing hop:

  • 503: the backend Service has no ready endpoints, or the Ingress names a Service or port that does not exist. The request never left the controller. Check kubectl get endpointslices -l kubernetes.io/service-name=<svc> and readiness.
  • 502: the controller reached an upstream and got something unusable: connection refused or reset, a keep-alive connection closed under it, an oversized header, or HTTPS spoken to a plain-HTTP port. The error line in the controller log names which.
  • 504: the controller waited proxy-read-timeout (or the connect timeout) and the upstream did not answer. The pod is alive and slow, or a NetworkPolicy or MTU problem is dropping packets.
  • 413: the body exceeded proxy-body-size; the pod never saw it.
  • 404 from the default backend: no rule matched host and path (check the Host header, wildcard scope, pathType and rewrites).
  • 308: the HTTP-to-HTTPS redirect; clients that do not follow redirects report it as an error.

The access log carries the evidence. ingress-nginx's default format ends with $request_time [$proxy_upstream_name] [$proxy_alternative_upstream_name] $upstream_addr $upstream_response_length $upstream_response_time $upstream_status $req_id: which backend was chosen (shop-api-8080), which pod IP, how long it took, and what the pod answered versus what the client received. A 499 means the client closed first. Read this line before the application logs, because it tells you whether the application was ever involved.

The debugging order is then mechanical:

  1. The controller access log line for the failing request (kubectl -n ingress-nginx logs deploy/ingress-nginx-controller | grep <path or req_id>).
  2. kubectl describe ingress for sync errors, admission rejections and the resolved backends; kubectl ingress-nginx backends shows what the controller believes the endpoints are.
  3. Endpoints and readiness of the backend Service.
  4. curl the pod IP and port directly from a debug pod with the same headers, then the Service, then through the controller with --resolve shop.example.com:443:<lb-ip>.
  5. Only now the application logs.

If the rendered configuration is in doubt, kubectl -n ingress-nginx exec deploy/ingress-nginx-controller -- cat /etc/nginx/nginx.conf shows exactly what the proxy is running, including which location block a path landed in.

Gateway API: roles, attachment, and what changes

Gateway API replaces one overloaded object with three, split along the people who own them:

  • GatewayClass (cluster-scoped, from the infrastructure provider or controller vendor) says which controller implements Gateways of this class.
  • Gateway (namespaced, owned by the platform team) is the listening surface: listeners with name, port, protocol, hostname (wildcards allowed), tls.certificateRefs, and allowedRoutes, which decides which namespaces may attach (namespaces.from: Same by default, All, or Selector with a label selector) and which route kinds.
  • HTTPRoute (namespaced, owned by the application team) attaches through parentRefs (Gateway name and namespace, optionally sectionName for one listener), declares hostnames that must intersect the listener's, and carries rules with typed matches (path Exact, PathPrefix or RegularExpression, headers, query parameters, method), filters (RequestHeaderModifier, ResponseHeaderModifier, RequestRedirect, URLRewrite, RequestMirror), timeouts, and backendRefs with weight, so a canary is a field rather than an annotation.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: { name: api, namespace: shop }
spec:
  parentRefs: [{ name: shared, namespace: infra, sectionName: https }]
  hostnames: [shop.example.com]
  rules:
    - matches: [{ path: { type: PathPrefix, value: /api } }]
      backendRefs:
        - { name: api, port: 8080, weight: 90 }
        - { name: api-canary, port: 8080, weight: 10 }

Crossing namespaces is explicit in both directions. The Gateway owner opens attachment with allowedRoutes; a route that is refused shows Accepted: False with reason NotAllowedByListeners in its status. A route (or a Gateway listener's certificate) that references a Service or Secret in another namespace needs a ReferenceGrant in the target namespace, or the route reports ResolvedRefs: False with RefNotPermitted. Conditions on the Gateway (Accepted, Programmed) and on each listener tell you whether the data plane is actually configured; read them before the controller logs.

Precedence is defined by the specification instead of by each controller: exact path over longest prefix, then method, then most header matches, then most query matches, then the older route by creation timestamp. Migration from Ingress can be incremental: run both APIs behind the same controller, or convert with ingress2gateway and cut over host by host.

Myths and facts

Myth: Creating an Ingress exposes the application.

Fact: Only a controller watching that IngressClass does; with the wrong class name or no default class, the Ingress sits with an empty ADDRESS and nothing listens.

Myth: pathType Prefix is string-prefix matching.

Fact: It matches element by element on /-separated segments: /api matches /api/v1 but not /apix, and a trailing slash on the rule is ignored.

Myth: A 502 means the pod crashed.

Fact: 502 means the controller reached an upstream and got something unusable: a closed keep-alive connection, an oversized header, a protocol mismatch, or a refused or reset connection. The controller's error line says which.

Myth: TLS Secrets go in the namespace where the controller runs.

Fact: The Secret must be in the Ingress's own namespace; the controller looks it up there and otherwise serves its default certificate. Sharing one certificate across namespaces means copying it, or terminating at a Gateway listener with a ReferenceGrant.

Myth: Raising the controller's proxy-read-timeout fixes 504s.

Fact: The shortest timeout in the chain wins, and the balancer in front has its own; long requests should become asynchronous rather than stretching every hop.

Myth: Annotations apply to the path they sit next to.

Fact: Annotations are Ingress-wide; rewrite-target or a timeout affects every path in the object. Split Ingresses per annotation set.

Myth: Gateway API is Ingress with new names.

Fact: It separates ownership (GatewayClass, Gateway, HTTPRoute), makes header matching, weights, mirroring and timeouts typed fields, gates cross-namespace use with allowedRoutes and ReferenceGrant, and reports why a route is not live in status conditions.

How pros do it

  • Set ingressClassName explicitly on every Ingress; never rely on a default class in a cluster that runs more than one controller.
  • Use one Ingress per distinct annotation set (rewrite, timeouts, body size); annotations are Ingress-scoped, and a shared object leaks one path's settings onto every other.
  • Make the application's keep-alive idle timeout longer than the controller's upstream keep-alive timeout, and bake the value into the base image or chart defaults so a library upgrade cannot silently reset it.
  • Set per-Ingress timeouts from the endpoint's p99 plus margin, and turn anything that legitimately takes longer than tens of seconds into an asynchronous job instead of raising timeouts through the whole chain.
  • Automate certificates with cert-manager, alert on expiry and on the controller serving its default certificate (a synthetic probe that checks the served SAN catches both).
  • Read the controller's access log line (upstream_status, upstream_addr, upstream_response_time) before the application's logs; it tells you which hop failed and whether the application was ever reached.
  • Adopt Gateway API for new routing: the platform team owns Gateway listeners and TLS, application teams own HTTPRoutes, and allowedRoutes uses a namespace label selector rather than All.
  • Treat the controller as the front door: several replicas spread across zones, a PodDisruptionBudget, resource requests sized from real traffic, and externalTrafficPolicy: Local or proxy protocol when client IPs matter.

Questions people ask

502 vs 503 vs 504: which one is my application's fault?

Read them as hops. 503: the controller had no ready endpoint to send to, so the request never left the proxy (check the EndpointSlice and readiness). 504: a pod was reached and did not answer within the proxy's read timeout, so it is slow or packets are being dropped. 502: a pod was reached and answered with something unusable, and the error text says which — a prematurely closed connection is a keep-alive mismatch, an oversized header is a buffer setting, refused is the pod not listening.

Browsers show the 'Kubernetes Ingress Controller Fake Certificate'. Why?

The controller found no certificate for that host and served its default. The Secret is missing from the Ingress's own namespace, has the wrong type or keys, or the host is not listed under spec.tls[].hosts. The controller log line Error obtaining X.509 certificate names the key it looked for; openssl s_client -servername shows what is actually served.

My websocket connections drop after exactly 60 seconds. What is that?

A timeout, and the exact number names whose: ingress-nginx defaults proxy-read-timeout and proxy-send-timeout to 60 s. Raise both by annotation on that Ingress only, then check the load balancer's idle timeout, which is the next hop to fire. The shortest timeout in the chain always wins.

I created an Ingress and nothing happens; ADDRESS is empty. Why?

No controller adopted it — an Ingress with no controller is just a document. Compare spec.ingressClassName with kubectl get ingressclass, confirm a default class exists if you left it out, and confirm the controller pods are running.

Do I need Gateway API, or is Ingress enough?

Ingress is enough for one team with host and path routing. Once several teams share an edge, or you need header routing, weighted canaries, mirroring or typed timeouts without controller-specific annotations, Gateway API's role split (platform owns the Gateway and TLS, teams own HTTPRoutes) and its status conditions pay for themselves.

I added rewrite-target and now my API returns 404 for everything. Why?

rewrite-target: / rewrites every matched URI to /, and annotations apply to every path in the Ingress. Use a regex path with a capture group and rewrite-target: /$2, and put the rewritten path in its own Ingress so the other paths are untouched — one Ingress per annotation set.

Why does the controller send traffic straight to pod IPs instead of the ClusterIP?

So it can balance per request rather than per connection, health-check upstreams itself and offer cookie affinity. It reads the EndpointSlices, which is why a readiness regression shows up as 503 within seconds; ingress-nginx's service-upstream annotation switches to the ClusterIP if you need kube-proxy's behaviour.

How do I route to a Service in another namespace?

Ingress cannot; backends are namespace-local, so create the Ingress in the Service's namespace. Gateway API can: the HTTPRoute references the Service across namespaces and the target namespace grants it with a ReferenceGrant.

Further reading

Drills · 9

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

"Browsers are showing the Kubernetes Ingress Controller Fake Certificate — what is wrong?" You added TLS to Ingress shop in namespace shop: spec.tls lists shop.example.com with secretName: shop-example-tls. kubectl get secret shop-example-tls -A finds the Secret only in namespace cert-manager, type kubernetes.io/tls. What is going on?

  1. The Ingress needs the ssl-redirect annotation before the controller will terminate TLS. ssl-redirect only controls the HTTP-to-HTTPS redirect; termination is configured by the tls section and its Secret.
  2. The Secret type is wrong; Ingress TLS requires an Opaque Secret with cert and key entries. kubernetes.io/tls with tls.crt and tls.key is exactly the required shape; the type is right and the namespace is wrong.
  3. The Secret must live in the Ingress's namespace: the controller looks up shop/shop-example-tls, finds nothing, logs Error obtaining X.509 certificate, and serves its default certificate for that host. Issue or copy the certificate into shop. Ingress TLS references are namespace-local by name; a Secret in another namespace is invisible to this Ingress, and the fallback is the controller's self-signed default.
  4. TLS Secrets must be in the controller's namespace so it can read them; move it to ingress-nginx. The controller has RBAC to read Secrets cluster-wide, but the API contract binds an Ingress to Secrets in its own namespace; the controller's namespace is irrelevant.
In short

The TLS Secret must be in the Ingress's own namespace (shop); the controller cannot see it in cert-manager, so it serves its default certificate.

Why

The controller resolves spec.tls[].secretName as <ingress namespace>/<name>, loads tls.crt and tls.key, and registers the certificate for the listed hosts so SNI can select it. A missing or unreadable Secret leaves the host without a certificate, and the controller serves its default self-signed one rather than refusing the handshake. The interview signal is knowing the namespace rule and reaching for the controller log and openssl s_client -servername as evidence instead of guessing at annotations.

The common mistake

Moving the Secret into the controller's namespace, or blaming the Secret type or a missing ssl-redirect annotation. The controller can read Secrets everywhere; the API binds an Ingress to Secrets in its own namespace only.

Read the docs

2 Answer out loud

A route starts returning errors. From the ingress controller's point of view, what do 502, 503 and 504 each mean, and in what order do you check things? Two to five sentences, as if a staff engineer were timing you.

In short

A strong answer says 503 is no ready endpoints, 502 is a bad reply from a reached pod, 504 is a timeout, and checks the controller log line first.

What a strong answer does
  • status semantics: 503 means the controller had no ready endpoint to send to (request never left the proxy); 502 means it reached an upstream and got refused, reset, a closed keep-alive connection or an oversized header; 504 means it waited its read timeout and got nothing; names the hop each one implicates.
  • method: Controller access log line first (upstream_status, upstream_addr, upstream_response_time, error text), then describe ingress and endpoints, then curl the pod directly with the same headers, then the Service, then the app logs; explains that this order proves whether the application was ever reached.
  • communication: Leads with the three codes as three hops, then a numbered order with what each step proves, no filler.
Why

Interviewers listen for whether you treat the controller as a hop with its own evidence rather than as a black box in front of "the backend". Three codes mapping to three hops, and a debugging order that starts with the controller's own log line and proves at each step whether the application was reached, is the shape of a strong answer.

The common mistake

Treating all three as 'the backend is down' and going straight to application logs or a restart. The controller's log line tells you whether the application was ever reached; skipping it costs the minutes that matter.

Read the docs

3 Read the output

What produced the 504, and whose setting fired?

$ kubectl -n ingress-nginx logs deploy/ingress-nginx-controller | grep 'POST /api/v1/reports'
10.0.3.7 - - [<time>] "POST /api/v1/reports HTTP/1.1" 504 160 "-" "curl/8.6.0" 512 60.003 [shop-api-8080] [] 10.244.2.19:8080 0 60.002 504 5f1c9e0d5a3b4c7e8f2a1b3c4d5e6f70

$ kubectl get endpointslices -n shop -l kubernetes.io/service-name=api
NAME        ADDRESSTYPE   PORTS   ENDPOINTS                AGE
api-x7k2p   IPv4          8080    10.244.2.19,10.244.4.8   9d

$ kubectl -n shop logs deploy/api | grep reports | tail -1
{"level":"info","msg":"report generated","path":"/api/v1/reports","duration_ms":84120}
  1. The pod crashed mid-request and the controller received a connection reset. A reset is logged as a 502 with an error line naming it; 504 is a timeout, and the application log shows the pod completed the report.
  2. The controller's proxy-read-timeout (60 s by default) fired: it waited 60.002 s on 10.244.2.19:8080, gave up and answered 504 while the pod kept working and finished the report after 84 s. The setting that fired belongs to the controller, not to the application. The upstream address is present, upstream_response_time is exactly the default read timeout, upstream_status is 504, and the application log shows the work completed later: a proxy timeout, not an application failure.
  3. The cloud load balancer's idle timeout expired and cut the connection. A balancer cutting the connection would not make the controller write a 504 with an upstream time that matches its own read timeout to the millisecond.
  4. The client gave up after 60 s and closed its connection. A client that closes first is logged as 499 by nginx-based controllers; 504 is the controller's own decision after its read timeout.
  5. The Service has no healthy endpoints, so the controller could not forward the request. No endpoints produces a 503 with an empty upstream address; here the log names a pod IP and a 60 s upstream time, and the slice lists two ready endpoints.
In short

The controller's own proxy-read-timeout (60 s) fired and it answered 504; the pod was alive and finished the report later.

Why

ingress-nginx's access log ends with the upstream name, address, response length, response time and status: [shop-api-8080] 10.244.2.19:8080 0 60.002 504 says the controller chose the api backend, sent the request to that pod, received nothing, and after 60 s (its proxy-read-timeout) answered 504 on its own. The pod was alive and slow, which the application log confirms. The interview signal is matching the measured 60.002 s to a specific hop's default rather than saying "the backend timed out" and treating 504 as the pod's fault.

The common mistake

Calling a 504 'the backend timed out' and going to the application logs, or reading it as no endpoints. The upstream address and the 60.002 s in the controller's own line say the pod was reached and the proxy gave up; no endpoints would be a 503 with an empty upstream.

Read the docs

4 Find what's broken

ingress-nginx serves this Ingress; Services web:80 and api:8080 exist with Ready endpoints. The site loads, but every call to /api/v1/orders returns the HTML home page with status 200, and so does /static/app.js. Which two lines are wrong, and what would you change?

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: shop
  namespace: shop
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/proxy-body-size: 10m
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - shop.example.com
      secretName: shop-example-tls
  rules:
    - host: shop.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80
          - path: /api
            pathType: Exact
            backend:
              service:
                name: api
                port:
                  number: 8080
In short

Line 7 (rewrite-target: /) sends every request to / and line 27 (pathType: Exact) stops /api sub-paths from reaching the api Service.

What's broken
  • Line 7: rewrite-target: / applies to every path in this Ingress (annotations are Ingress-scoped, not per-path) and, without a capture group, rewrites every matched URI to /, so /static/app.js reaches web as GET /.
  • Line 27: pathType: Exact on /api matches only the literal /api, so /api/v1/orders falls through to the / Prefix rule and is sent to web.
Why

Two independent mechanisms produce one confusing symptom. Path matching is element-wise for Prefix and literal for Exact, so the API sub-paths never reach the api rule and fall to the catch-all; and controller annotations are properties of the whole Ingress, so a bare rewrite-target: / turns every request into a request for /. proxy-body-size: 10m (line 8) is a harmless per-Ingress limit, ingressClassName: nginx (line 10) is exactly what makes the controller adopt the object, and number: 8080 (line 32) matches the Service. The interview signal is reasoning about the rendered proxy configuration (which location block, which rewrite) rather than the YAML's apparent intent.

Read the docs

5 Scenario: what do you do next?

It is 10:14. The checkout API in namespace shop (six replicas behind ingress-nginx) was deployed at 09:50 with a new HTTP server library. Alert: the 5xx ratio for checkout.example.com is 0.8% against a 0.1% SLO. Every error is a 502, spread evenly across all pods and across the whole 24 minutes. Pods are Running and Ready, restarts are zero, CPU and memory are flat.

Step 1. You have the controller's access and error logs open. What do you look at first?

  1. The 502 lines' error text, upstream_addr and upstream_response_time, and whether the failures cluster on one pod or spread evenly; thirty seconds of reading that classifies the failure. The controller's error line distinguishes refused (pod not listening), reset, oversized header, and a prematurely closed keep-alive connection; that classification decides which mitigation can work at all.
  2. Restart the ingress controller pods to clear stale upstream connections. Restarting the front door for every host in the cluster on an unclassified symptom risks a bigger outage than the one you have; the stale-connection theory is a guess.
  3. Roll back the Deployment immediately; the timing matches the deploy. Rollback may well be the right mitigation, but the error line takes seconds to read and tells you whether a rollback will help (a header-size or body-size 502 would survive it). Read first, then act.
  4. Scale checkout from six to twelve replicas. CPU and memory are flat and errors are evenly spread; nothing points at saturation, and more replicas do not change a per-connection failure.

Step 2. Every failing line reads upstream prematurely closed connection while reading response header from upstream, upstream_response_time is 0.001, and the failed request is always the first on a connection idle for about five seconds. The new library's keep-alive idle timeout defaults to 5 s; the previous server was configured for 65 s; the controller's upstream-keepalive-timeout is 60 s. What is your mitigation?

  1. Lower the controller's upstream-keepalive-timeout in its ConfigMap to 3 s. A cluster-wide change to the front door during an incident, affecting every backend's connection reuse; the invariant belongs with the application, and other services may have tuned to the 60 s value.
  2. Enable proxy-next-upstream retries on 502 so the controller transparently retries the request. Retrying a POST that may have reached the application risks duplicate orders, which is why nginx does not retry non-idempotent requests by default; and the race would still be there.
  3. Roll the Deployment back to the previous image now, then re-release with the new library's idle timeout set above 60 s (75 s, say), verified in a canary before full rollout. The smallest reversible change that removes the race, and the real fix is a one-line setting that can be validated calmly afterwards.
  4. Disable upstream keep-alive cluster-wide by setting upstream-keepalive-connections to 0. It removes the race but adds a TCP handshake to every request for every application on the cluster; a tradeoff not worth paying for one service's missing setting.

Step 3. Rollback finished at 10:22 and the 502s are gone. In the postmortem, which action item do you propose?

  1. Encode the invariant as a mechanism: application idle timeout greater than the controller's upstream keep-alive timeout, set in the shared base image or chart defaults and checked in CI; a canary stage gated on the 5xx ratio and the controller's prematurely closed count; and an alert on 502s broken down by error reason. A default that cannot be forgotten, a rollout gate that catches the regression at one pod, and detection by mechanism: each removes a way for this class of failure to recur.
  2. Ask teams to review keep-alive settings whenever they change HTTP libraries. A reminder, not a mechanism; the next library upgrade will forget it exactly as this one did.
  3. Replace ingress-nginx with a controller that does not reuse upstream connections. Every production proxy reuses connections; the race exists with any of them unless the timeouts are ordered, and a controller migration is a large change for a one-line setting.
In short

Read the controller's 502 error text first, roll the Deployment back, then make the app keep-alive timeout longer than the controller's 60 s.

Why

The mechanism is a race between two idle timers: the controller keeps an upstream connection for 60 s, the application now closes it after 5 s, and any request that reuses the connection in the window between those two closes fails with a prematurely closed connection, evenly across pods and time. The interview signal is classifying the 502 from the controller's error text before acting, mitigating with the smallest reversible change, and proposing the invariant as a default plus a rollout gate rather than a reminder.

Read the docs

6 Pick the strongest answer

The platform team runs a Gateway shared in namespace infra with an https listener. An application team creates an HTTPRoute in namespace shop with parentRefs: [{name: shared, namespace: infra, sectionName: https}] and hostnames: [shop.example.com]. Traffic does not flow. kubectl describe httproute -n shop shows, under the parent's status, Accepted: False with reason NotAllowedByListeners. What is the mechanism and the correct fix?

  1. Set hostnames on the HTTPRoute to match the listener's hostname exactly, because a mismatch prevents acceptance. A hostname mismatch produces the reason NoMatchingListenerHostname; NotAllowedByListeners specifically means the namespace or route kind is not permitted by allowedRoutes.
  2. Create a ReferenceGrant in infra that allows HTTPRoutes from shop to reference the Gateway. ReferenceGrant governs cross-namespace backendRefs and certificate references, not attachment to a Gateway; attachment is controlled only by the listener's allowedRoutes.
  3. Move the HTTPRoute into infra, since routes must live in the same namespace as their Gateway. Routes may attach across namespaces whenever the listener allows it; moving the route would work but defeats the role split and requires the app team to write into the platform namespace.
  4. The listener's allowedRoutes.namespaces.from is Same (the default), so only routes in infra may attach. The Gateway owner opens attachment with from: Selector and a namespace label selector (or All); the app team cannot fix this from shop. Attachment is gated by the Gateway owner's allowedRoutes, and the status reason says exactly that; the change belongs on the Gateway.
  5. Add a gatewayClassName to the HTTPRoute so the controller knows which implementation should program it. Only Gateways have a gatewayClassName; a route is programmed by whichever controller owns the Gateway it attaches to.
In short

The Gateway listener's allowedRoutes only allows routes from its own namespace; the Gateway owner must open it with a namespace selector or All.

Why

Gateway API makes cross-namespace attachment an explicit handshake: the route asks with parentRefs, and the Gateway's listener answers with allowedRoutes (namespaces Same, All, or Selector, plus permitted kinds). A refused route is not an error in the route; it is a policy decision surfaced as a status condition with a reason, so the fix belongs to the Gateway owner. ReferenceGrant is the other direction of the handshake, used when a route or listener references a Service or Secret in another namespace. The interview signal is reading the status reason and knowing which object, and which team, owns the fix.

Read the docs

7 Design round

You run one shared cluster for thirty product teams. A single ingress-nginx serves about two hundred Ingress objects that teams edit directly, and the last quarter's incidents include two teams claiming the same hostname, an Ingress-wide rewrite that hollowed out an API, an expired certificate nobody owned, and one team's ten-minute upload timeout that was applied globally. Design the ingress platform you would move to, how the migration proceeds without downtime, and how you would prove it works.

  • One shared edge and one wildcard DNS zone; no per-team load balancers.
  • Teams must not need write access outside their own namespace.
  • The two hundred existing Ingresses keep working until each team migrates; no flag day.
  • No service mesh.
In short

A strong answer moves to Gateway API with a platform-owned Gateway, team-owned HTTPRoutes, central TLS, bounded route settings, and a per-host migration with checks.

A strong answer covers
  • Splits ownership with Gateway API: platform owns GatewayClass, a Gateway with per-protocol listeners and TLS, and admits namespaces through allowedRoutes with a label selector; teams own HTTPRoutes in their namespaces.
  • Centralises TLS on the Gateway listeners with cert-manager issuing into the platform namespace (wildcard or per-host), expiry alerting, and ReferenceGrant only where a team must bring its own certificate.
  • Turns timeouts, body size and rewrites into policy: platform defaults at the listener or controller level, route-level timeouts and typed filters for per-route needs, and an admission policy that bounds what a route may set.
  • Prevents hostname collisions by mechanism: one namespace per hostname enforced by admission (ValidatingAdmissionPolicy or a policy engine) and a documented ownership registry, with Gateway API's deterministic precedence for overlaps.
  • Migrates incrementally: Ingress and HTTPRoute served side by side (same controller or a second controller with per-host DNS cutover), conversion with ingress2gateway, canary per hostname with weighted backendRefs, and a rollback path per host.
  • States verification: synthetic probes per hostname checking status, latency and served certificate; alerts on route Accepted/ResolvedRefs false and Gateway Programmed false; per-route 5xx and p99 dashboards; and a named tradeoff (typed fields vs the annotations teams relied on, or platform control vs team autonomy).
What a strong answer does
  • design quality: Role split with allowedRoutes selectors, centralised TLS with alerting, timeouts and sizes as bounded policy, admission-enforced hostname ownership, an incremental per-host migration with canaries, and a verification plan.
  • tradeoffs: Two or more tradeoffs weighed with a decision: team autonomy vs platform bounds, typed fields vs annotation features some teams need, a second controller's blast radius vs a shared one's, and when a team should get its own Gateway.
  • communication: Restates the four incidents as requirements, maps each to a mechanism, then migration, verification and the decision, with numbers where they matter.
Why

The primitives interviewers expect: an ownership split (GatewayClass, Gateway, HTTPRoute) that makes cross-namespace attachment explicit, TLS and policy centralised where the platform can own and alert on them, route-scoped settings instead of object-wide annotations, admission enforcement for hostname ownership, an incremental migration with canaries and per-host rollback, and a verification plan tied to the original incidents. Naming what teams lose (annotation features, direct edge control) and deciding anyway is the staff-level signal.

Read the docs

8 Quick recall

Every pod behind an Ingress route is failing its readiness probe, so the backend Service has no ready endpoints. Which HTTP status does the controller return to clients?

In short

It returns 503 Service Unavailable.

Accepted

503 · 503 Service Unavailable · Service Unavailable

Why

With no ready endpoint to forward to, the controller answers 503 Service Unavailable itself; the request never reaches a pod. 502 means an upstream was reached and answered badly, 504 means it was reached and did not answer in time.

9 Pick the strongest answer

A team writes one rule, path: /api with pathType: Prefix, and expects it to catch "everything under api". Which of these request paths does the rule NOT route?

  1. /apis/v1 Prefix matching is element-wise on /-separated segments: a first segment that merely starts with the rule's segment is a different segment, so this is not a match despite sharing a string prefix.
  2. /api/v1?page=2 Path matching considers only the path; the query string is not part of the comparison, so this matches exactly as it would without it.
  3. /api/ A trailing slash does not change the path elements; the rule matches with or without it.
  4. /api A request equal to the prefix itself matches: every element of the rule is an element-wise prefix of the request.
In short

Prefix matches whole path segments, so the rule does not match a path whose first segment is the prefix with extra letters added.

Why

Prefix splits both the rule and the request on / and requires every rule element to equal the corresponding request element, so /api matches /api, /api/ and /api/v1 but not /apis/v1 or /apix. Exact compares the whole string; ImplementationSpecific hands the string to the controller for regex or other semantics. The interview signal is knowing that "prefix" here means path-element prefix, and that on overlapping rules the longest match wins with Exact beating Prefix on a tie.

Read the docs

Next lesson Multi-tenancy: namespaces, ResourceQuota, LimitRange, PriorityClass, noisy neighbours, and when to split clusters
Drill · Ingress and Gateway API
0:00

Loading…