TExcelTAD
Home › Kubernetes › The Gateway API

The Gateway API

The Ingress & Gateway API lesson introduced the three roles (GatewayClass, Gateway, HTTPRoute) and a weighted canary. This lesson treats the Gateway API (gateway.networking.k8s.io/v1) as what it has become: the standard way to get traffic into a cluster, and increasingly between services inside it. With the community ingress-nginx controller retired since March 2026 (no more releases or security fixes), Gateway API is the recommended migration path, and most teams writing new routing config today write Gateway API resources.

Why a new API?

Ingress packs everything into one object and leaves anything beyond host + path to controller-specific annotations, so an ingress-nginx config doesn't work on Traefik. Gateway API fixes three things:

Problem with Ingress Gateway API answer
One object for infra and app settings Gateway (platform team) and HTTPRoute (app teams) are separate, with RBAC per resource
Features hidden in annotations Header/method/query matching, weights, redirects, rewrites, mirroring and timeouts are typed fields
HTTP only HTTPRoute, GRPCRoute, TLSRoute, TCPRoute, UDPRoute
Status says little Every route reports per-parent conditions: Accepted, ResolvedRefs; Gateways report Programmed

Implementations include Envoy Gateway, Istio, Cilium, NGINX Gateway Fabric, Traefik, Kong, HAProxy and the cloud load balancers of GKE, EKS (AWS Load Balancer Controller) and AKS. The API is versioned separately from Kubernetes: you install the CRDs (standard or experimental channel) that your implementation supports.

bash
kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.4.0/standard-install.yaml

A shared Gateway

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: public
  namespace: infra
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod     # see the cert-manager lesson
spec:
  gatewayClassName: eg
  listeners:
    - name: http
      protocol: HTTP
      port: 80
      allowedRoutes:
        namespaces: {from: Same}            # only the HTTP->HTTPS redirect lives here
    - name: shop
      protocol: HTTPS
      port: 443
      hostname: "*.shop.example.com"
      tls:
        mode: Terminate
        certificateRefs: [{name: shop-wildcard-tls}]
      allowedRoutes:
        namespaces:
          from: Selector
          selector:
            matchLabels: {gateway-access: shop}
    - name: docs
      protocol: HTTPS
      port: 443
      hostname: docs.example.com
      tls:
        certificateRefs: [{name: docs-tls}]
      allowedRoutes:
        namespaces: {from: All}

A route attaches to a Gateway with parentRefs (optionally naming one listener with sectionName). It is accepted only if the listener allows the route's namespace and the hostnames intersect. A listener *.shop.example.com accepts a route for api.shop.example.com; a route for *.shop.example.com on a listener for api.shop.example.com is narrowed to that one name; a route for shop.example.com (no subdomain) matches neither. The model computes attachment and the effective hostnames for each route:

python · try it yourself
LISTENERS = [
    {"name": "shop", "hostname": "*.shop.example.com", "from": "Selector", "selector": "shop"},
    {"name": "docs", "hostname": "docs.example.com", "from": "All"},
]
NAMESPACES = {"storefront": {"gateway-access": "shop"}, "docs": {}, "sandbox": {}}

def covers(wildcard, name):
    # "*.shop.example.com" covers one or more labels in front of shop.example.com
    return wildcard.startswith("*.") and name.endswith(wildcard[1:]) and not name.startswith("*.")

def host_match(listener, route_host):
    """Effective hostname of a route hostname on a listener, or None."""
    if listener == route_host or covers(listener, route_host):
        return route_host
    if covers(route_host, listener):          # route wildcard narrowed to the listener name
        return listener
    return None

def ns_allowed(listener, ns):
    if listener["from"] == "All":
        return True
    return NAMESPACES[ns].get("gateway-access") == listener.get("selector")

def attach(route):
    results = []
    for l in LISTENERS:
        if not ns_allowed(l, route["ns"]):
            results.append(f"{l['name']}: NotAllowedByListeners")
            continue
        hosts = [h for h in (host_match(l["hostname"], rh) for rh in route["hostnames"]) if h]
        results.append(f"{l['name']}: Accepted {hosts}" if hosts else f"{l['name']}: NoMatchingListenerHostname")
    return results

routes = [
    {"name": "storefront/api", "ns": "storefront", "hostnames": ["api.shop.example.com"]},
    {"name": "storefront/all", "ns": "storefront", "hostnames": ["*.shop.example.com", "shop.example.com"]},
    {"name": "docs/site", "ns": "docs", "hostnames": ["*.example.com"]},
    {"name": "sandbox/try", "ns": "sandbox", "hostnames": ["try.shop.example.com"]},
]
for r in routes:
    print(f"{r['name']:16}", " | ".join(attach(r)))
storefront/api   shop: Accepted ['api.shop.example.com'] | docs: NoMatchingListenerHostname
storefront/all   shop: Accepted ['*.shop.example.com'] | docs: NoMatchingListenerHostname
docs/site        shop: NotAllowedByListeners | docs: Accepted ['docs.example.com']
sandbox/try      shop: NotAllowedByListeners | docs: NoMatchingListenerHostname

kubectl get httproute -A doesn't show this; kubectl describe httproute checkout -n storefront (or -o yaml) does, under status.parents[].conditions. Here a route was accepted but one of its backends is not allowed (sample output):

text
Status:
  Parents:
    Conditions:
      Type:     Accepted
      Status:   True
      Reason:   Accepted
      Type:     ResolvedRefs
      Status:   False
      Reason:   RefNotPermitted
      Message:  backendRef payments/charge not permitted by any ReferenceGrant
    Controller Name:  gateway.envoyproxy.io/gatewayclass-controller
    Parent Ref:
      Name:          public
      Namespace:     infra
      Section Name:  shop

Routes, matches and precedence

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: api
  namespace: storefront
spec:
  parentRefs: [{name: public, namespace: infra, sectionName: shop}]
  hostnames: [api.shop.example.com]
  rules:
    - matches: [{path: {type: Exact, value: /healthz}}]
      backendRefs: [{name: health, port: 8081}]
    - matches:
        - path: {type: PathPrefix, value: /v2}
          headers: [{name: x-beta, value: "1"}]
      backendRefs: [{name: api-v2, port: 80}]
    - matches:
        - path: {type: PathPrefix, value: /v2}
          method: POST
      backendRefs: [{name: api-v2-writes, port: 80}]
    - matches: [{path: {type: PathPrefix, value: /}}]
      filters:
        - type: RequestHeaderModifier
          requestHeaderModifier:
            set: [{name: x-served-by, value: gateway}]
      backendRefs: [{name: api-v1, port: 80}]
      timeouts: {request: 10s}

Unlike a firewall, rule order doesn't decide. When several matches fit a request, the spec defines the winner: an Exact path beats any prefix, then the longest PathPrefix, then a match with a method, then the most header matches, then the most query-parameter matches. Remaining ties go to the oldest route, then alphabetical order. The model ranks candidates exactly that way:

python · try it yourself
MATCHES = [  # (rule, path type, path value, method, headers)
    ("health", "Exact", "/healthz", None, {}),
    ("v2-beta", "PathPrefix", "/v2", None, {"x-beta": "1"}),
    ("v2-writes", "PathPrefix", "/v2", "POST", {}),
    ("v1", "PathPrefix", "/", None, {}),
]

def path_ok(kind, value, path):
    if kind == "Exact":
        return path == value
    return value == "/" or path == value or path.startswith(value.rstrip("/") + "/")

def rank(m):
    rule, kind, value, method, headers = m
    return (kind == "Exact", len(value), method is not None, len(headers))

def route(method, path, headers=None):
    headers = headers or {}
    fits = [m for m in MATCHES if path_ok(m[1], m[2], path)
            and (m[3] is None or m[3] == method)
            and all(headers.get(k) == v for k, v in m[4].items())]
    return max(fits, key=rank)[0] if fits else "404"

requests = [("GET", "/healthz"), ("GET", "/healthz/deep"), ("GET", "/v2/items"),
            ("POST", "/v2/items"), ("GET", "/v2/items", {"x-beta": "1"}),
            ("POST", "/v2/items", {"x-beta": "1"}), ("GET", "/v20")]
for req in requests:
    method, path, *h = req
    print(f"{method:4} {path:13} {str(h[0]) if h else '':16} -> {route(method, path, h[0] if h else None)}")
GET  /healthz                       -> health
GET  /healthz/deep                  -> v1
GET  /v2/items                      -> v1
POST /v2/items                      -> v2-writes
GET  /v2/items     {'x-beta': '1'}  -> v2-beta
POST /v2/items     {'x-beta': '1'}  -> v2-writes
GET  /v20                           -> v1

A few lines deserve a second look. A plain GET /v2/items fell through to v1: both /v2 matches carry an extra condition (a header or a method), and every condition inside one match must hold. /v20 went to v1, because PathPrefix compares whole path segments, as Ingress's Prefix does. And POST /v2/items with x-beta: 1 matched both /v2 rules; the method match outranks the header match, so it went to v2-writes. If that's not what you want, add the header to the method rule too.

Filters are typed: RequestRedirect (the classic HTTP→HTTPS redirect on the port-80 listener), URLRewrite (strip /api before forwarding), RequestHeaderModifier/ResponseHeaderModifier, and RequestMirror (copy traffic to a shadow service and ignore its answers).

Cross-namespace references

A route may attach to a Gateway in another namespace when the listener allows it. Pointing a backendRef at a Service in another namespace needs consent from that namespace's owner, a ReferenceGrant:

yaml
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: storefront-may-call-charge
  namespace: payments                    # lives in the namespace being referenced
spec:
  from:
    - {group: gateway.networking.k8s.io, kind: HTTPRoute, namespace: storefront}
  to:
    - {group: "", kind: Service, name: charge}

Without it, the route reports ResolvedRefs: False / RefNotPermitted and requests that would go to that backend get a 500. The same handshake lets a Gateway use a TLS Secret from another namespace.

Progressive delivery with weights

backendRefs weights are relative (90/10, or 9/1); a weight of 0 keeps a backend configured but idle. Tools such as Flagger and Argo Rollouts change those weights step by step and watch metrics. A model of such a controller, with fixed error rates per step:

python · try it yourself
STEPS = [5, 25, 50, 100]          # canary weight per step
MAX_ERROR_RATE = 0.01

def run_canary(error_rates):
    weights = {"api-v1": 100, "api-v2": 0}
    for step, canary in enumerate(STEPS):
        weights = {"api-v1": 100 - canary, "api-v2": canary}
        err = error_rates[step]
        verdict = "ok" if err <= MAX_ERROR_RATE else "FAIL"
        print(f"  step {step + 1}: weights {weights}  v2 errors {err:.1%}  {verdict}")
        if verdict == "FAIL":
            weights = {"api-v1": 100, "api-v2": 0}
            return f"rolled back -> {weights}"
    return f"promoted -> {{'api-v2': 100}} (v1 can be removed)"

print("release 2.4.1:")
print("  " + run_canary([0.002, 0.004, 0.003, 0.002]))
print("release 2.5.0:")
print("  " + run_canary([0.003, 0.021, 0.0, 0.0]))
release 2.4.1:
  step 1: weights {'api-v1': 95, 'api-v2': 5}  v2 errors 0.2%  ok
  step 2: weights {'api-v1': 75, 'api-v2': 25}  v2 errors 0.4%  ok
  step 3: weights {'api-v1': 50, 'api-v2': 50}  v2 errors 0.3%  ok
  step 4: weights {'api-v1': 0, 'api-v2': 100}  v2 errors 0.2%  ok
  promoted -> {'api-v2': 100} (v1 can be removed)
release 2.5.0:
  step 1: weights {'api-v1': 95, 'api-v2': 5}  v2 errors 0.3%  ok
  step 2: weights {'api-v1': 75, 'api-v2': 25}  v2 errors 2.1%  FAIL
  rolled back -> {'api-v1': 100, 'api-v2': 0}

Beyond north-south

  • GRPCRoute matches on gRPC service and method instead of paths.
  • TLSRoute routes by SNI without terminating TLS (passthrough), useful for databases or apps that must hold their own keys.
  • BackendTLSPolicy makes the Gateway speak TLS to the backend and says which CA and hostname to verify.
  • Mesh (GAMMA): an HTTPRoute whose parentRefs names a Service instead of a Gateway configures east-west traffic in a service mesh, so retries, timeouts and canaries between services use the same API.

Migrating from Ingress is mostly mechanical: the ingress2gateway tool reads Ingress objects (including common ingress-nginx annotations) and prints equivalent Gateway and HTTPRoute YAML to review.

Learn more: TLS with cert-manager · Services · Network Policies

Test yourself

Two HTTPRoute rules match GET /v2/items: PathPrefix / and PathPrefix /v2. Which wins?

  1. The one listed first
  2. PathPrefix /v2, the longer prefix
  3. PathPrefix /, the more general one
  4. Traffic is split between them

An HTTPRoute in namespace storefront sends traffic to Service charge in namespace payments. What is required?

  1. Nothing
  2. A ReferenceGrant in payments allowing HTTPRoutes from storefront
  3. A ClusterRole binding
  4. A NetworkPolicy in storefront

A listener has hostname: "*.shop.example.com". Which route hostname can attach to it?

  1. shop.example.com
  2. api.shop.example.com
  3. example.com
  4. api.example.com