Advanced Gateway API usage

Updated at:

Basic Gateway API configurations cannot address scenarios such as custom instance parameters, complex route matching, and health checks in ACK clusters that use the ALB Ingress Controller. The advanced configurations of GatewayClass, HTTPRoute, AlbInstance, AlbRule, and AlbServerGroup let O&M engineers and developers handle complex traffic management.

GatewayClass type comparison

The ALB Ingress Controller provides two GatewayClass types: alb and alb-extensible, which distinguish different Application Load Balancer (ALB) instance editions.

GatewayClass

Scenarios

Features

alb

ALB standard edition instances

Provides standard ALB load balancing and routing capabilities with simple configuration, and suits most business scenarios

alb-extensible

ALB extensible edition instances

Based on service extension capabilities, provides authentication, content-based advanced routing, and AI-native features such as multi-model proxy and load-aware routing

Recommendation: The alb GatewayClass (ALB standard edition) is sufficient for most scenarios. When you need the authentication provided by service extensions, content-based advanced routing, or AI-native features such as multi-model proxy and load-aware routing, use the alb-extensible GatewayClass (ALB extensible edition). For details about the two editions, see Application Load Balancer (ALB) and ALB Extensible Edition overview.

Important

Switching the GatewayClass is not supported after a Gateway is created. That is, you cannot modify spec.gatewayClassName to switch between alb and alb-extensible. Select an appropriate GatewayClass based on your business requirements before you create a Gateway. To change the deployment mode, create a new Gateway with the target GatewayClass and complete the configuration migration.

Configure listener protocols

A Gateway supports two listener protocols: HTTP and HTTPS.

HTTP listener

An HTTP listener exposes a plaintext HTTP traffic entry on a Gateway. In spec.listeners, you declare protocol: HTTP and the corresponding port. The controller then creates the corresponding HTTP listener configuration for the Gateway and attaches the HTTPRoute rules that meet the conditions to this listener.

In the following example, the http80 listener uses port 80, and hostname is set to *.ingress.top, which means that only Routes whose Host matches this wildcard domain name are handled. allowedRoutes.namespaces.from: Same means that only Routes in the same namespace as the Gateway are allowed to bind to this listener.

Important

Whether a listener configuration takes effect depends not only on whether the YAML passes basic validation, but also on whether the controller subsequently builds and delivers it successfully. Issues such as listener conflicts, invalid protocol and port combinations, or mismatched Route binding scopes are usually reflected in the Gateway status.listeners as abnormal conditions such as Accepted, Programmed, and ResolvedRefs.

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: alb-test
  namespace: default
spec:
  gatewayClassName: alb
  listeners:
    - name: http80
      port: 80
      protocol: HTTP
      hostname: '*.ingress.top'
      allowedRoutes:
        namespaces:
          from: Same

HTTPS listener

An HTTPS listener exposes a TLS-encrypted traffic entry on a Gateway. A common scenario is that the Gateway performs TLS termination (TLS Terminate) and then forwards the decrypted HTTP requests to backend Services.

When you configure an HTTPS listener, specify protocol: HTTPS, the listener port, tls.mode: Terminate, and tls.certificateRefs to reference the certificate Secret. In the following example, the https443 listener uses port 443 and provides the certificate through the ingress.top Secret to handle HTTPS requests under the *.ingress.top domain name. allowedRoutes.namespaces.from: All indicates that Routes in any namespace are allowed to bind to this listener, but cross-namespace references to other resources must still meet the authorization constraints of Gateway API.

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: alb-test
  namespace: default
spec:
  gatewayClassName: alb
  listeners:
    - name: http80
      port: 80
      protocol: HTTP
      hostname: '*.ingress.top'
      allowedRoutes:
        namespaces:
          from: Same
    - name: https443
      protocol: HTTPS
      port: 443
      hostname: "*.ingress.top"
      allowedRoutes:
        namespaces:
          from: All
      tls:
        mode: Terminate
        certificateRefs:
          - kind: Secret
            name: ingress.top

Extend ALB instance configurations

AlbInstance is a Kubernetes CustomResourceDefinition (CRD) that provides instance-level configurations for ALB Gateways in Gateway API. Use AlbInstance to customize the properties of an ALB instance, such as the network type, the zone-to-vSwitch mappings, and access logs, without modifying the Gateway resource itself.

AlbInstance is associated with a Gateway through the spec.infrastructure.parametersRef field of the Gateway.

Important

AlbInstance is a namespace-scoped resource. It must reside in the same namespace as the Gateway, and cross-namespace references are not supported.

Important

Creating a Gateway creates an ALB instance. The resources referenced in the examples, such as elastic IP addresses (EIPs), Simple Log Service projects and Logstores, and Tracing Analysis resources, also incur separate fees. For the billing composition and pricing of ALB instances, see ALB billing. When you no longer use these resources, promptly delete the Gateway, AlbInstance, and other resources to avoid ongoing fees.

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: alb-test
  namespace: default
spec:
  gatewayClassName: alb
  infrastructure:
    parametersRef:
      group: alibabacloud.com
      kind: AlbInstance
      name: alb-instance-example
  listeners:
    - name: http80
      port: 80
      protocol: HTTP
      hostname: '*.ingress.top'
      allowedRoutes:
        namespaces:
          from: Same
    - name: https443
      protocol: HTTPS
      port: 443
      hostname: "*.ingress.top"
      allowedRoutes:
        namespaces:
          from: All
      tls:
        mode: Terminate
        certificateRefs:
          - kind: Secret
            name: ingress.top
---
apiVersion: alibabacloud.com/v1
kind: AlbInstance  
metadata:
  name: alb-instance-example
  namespace: default 
spec:
  config:
    name: alb-instance-name
    addressType: Internet # addressType parameter is parsed only when the ALB instance is created. Subsequent updates to the ALB instance have no effect.
    addressIpVersion: Ipv4 # addressIpVersion parameter is parsed only when the ALB is created. Subsequent updates to the ALB have no effect.
    resourceGroupId: "rg-aekzc25pxxx"
    zoneMappings: # zoneMappings parameter is parsed only when the ALB instance is created. Subsequent updates to the ALB instance have no effect.
    - vSwitchId: vsw-dpqqskqxxxxxxxxxx
      allocationId: eip-hdqodgqxxxxxxxxxx
    - vSwitchId: vsw-dhkqdgdxxxxxxxxxx
      allocationId: eip-hn31kckxxxxxxxxxx
    accessLogConfig:        
      logProject: "test"
      logStore: "alb_test"
    tags:
      - key: example-key
        value: example-value

Configure ALB listener properties

The spec.listeners of a Gateway declares only the protocol, port, hostname, and TLS certificate of a listener. To adjust other properties of an ALB listener, such as the listener description, idle connection timeout, request timeout, Gzip compression, TLS security policy, HTTPS mutual authentication, extended certificates, X-Forwarded-* header fields, logging and tracing, and listener tags, configure them through spec.listeners in the AlbInstance associated with the Gateway.

The matching rules are as follows:

  • protocol (case-insensitive) and port are the same as those of a listener in the Gateway spec.listeners. In that case, this configuration item applies to the corresponding ALB listener.

  • When multiple listeners in a Gateway use the same protocol and port (for example, listeners split by different hostnames), they correspond to the same ALB listener and share the same configuration item in AlbInstance.

  • Items that do not match any Gateway listener are ignored, and no ALB listener is created for them separately. The creation and deletion of listeners always follow the Gateway spec.listeners.

  • Duplicate items with both the same protocol and the same port are not allowed in one AlbInstance. When duplicates exist, the entire reconciliation of the Gateway fails. In the status.listeners of the corresponding Gateway listener, the ResolvedRefs condition is False and the reason is Invalid, and the configurations on ALB remain unchanged.

Note the following items:

  • Fields that are not configured use the controller default values and are not delivered as zero values. After you remove a configured field from AlbInstance, the ALB listener reverts to the default value of that field. The following two types of fields are exceptions:

    • In xForwardedForConfig, after you delete xForwardedForProcessingMode, existing listeners retain the current X-Forwarded-For configuration on ALB.

    • After you delete caCertificates or leave it empty, the controller no longer manages the CA certificate list, and the CA certificates already associated on ALB are retained.

  • When the AlbInstance listener configuration is invalid (for example, an empty certificate ID), the entire reconciliation of the Gateway fails and no configuration on ALB is modified, and the error is reflected in the status.listeners of the corresponding Gateway listener, such as InvalidCertificateRef.

  • securityPolicyId, caEnabled, and caCertificates take effect only on HTTPS listeners and are ignored when configured on HTTP listeners. Gateway API supports only HTTP and HTTPS listeners, not QUIC listeners.

  • An ALB instance created by a Gateway is an ACK-managed resource. Do not modify the listener configuration directly in the ALB console; otherwise, the controller overwrites your changes. Make all listener property changes by modifying AlbInstance.

Configure timeouts, Gzip compression, and listener tags

The following example sets the listener description, idle connection timeout, request timeout, Gzip compression, and listener tags on the HTTP 80 and HTTPS 443 listeners, and specifies a TLS security policy for the HTTPS listener.

apiVersion: alibabacloud.com/v1
kind: AlbInstance
metadata:
  name: alb-instance-example
  namespace: default
spec:
  listeners:
    - protocol: HTTP
      port: 80
      description: http-80-listener
      idleTimeout: 30
      requestTimeout: 120
      gzipEnabled: false
      tags:
        - key: example-key
          value: example-value
    - protocol: HTTPS
      port: 443
      description: https-443-listener
      idleTimeout: 60
      requestTimeout: 180
      gzipEnabled: true
      securityPolicyId: tls_cipher_policy_1_2

requestTimeout is the request timeout. After a client sends a request, if the backend server does not respond within the specified period, ALB stops waiting and returns an HTTP 504 error code to the client. This value does not limit the transmission duration of the response content.

The unit of idleTimeout (idle connection timeout) and requestTimeout (request timeout) is seconds. The valid values of both are [1, 600], and the default values are 15 and 60 respectively. To set a value greater than 600 seconds, submit a ticket to apply for a quota. If idleTimeout is set too small, idle connections are disconnected early, which affects the reuse of persistent connections. If it is set too large, listener connection resources are occupied for a long time.

Configure the X-Forwarded-For header field

Use xForwardedForConfig to configure the X-Forwarded-* header fields that ALB appends or processes when it forwards requests. For example, X-Forwarded-For carries the real client IP and X-Forwarded-Proto carries the listener protocol.

xForwardedForProcessingMode sets the processing mode of the X-Forwarded-For header field:

Value

Description

append

Append. ALB appends the client IP to the end of the X-Forwarded-For header field and then forwards the request to the backend.

remove

Delete. ALB removes the X-Forwarded-For header field from the request and then forwards the request to the backend.

preserve

Retain. ALB does not modify the X-Forwarded-For header field and forwards it to the backend as is.

Note
  • For a listener newly created by a Gateway, when xForwardedForProcessingMode is not set, the default value is append, which stays consistent with the listeners created by ALB Ingress.

  • For listeners that already existed before the upgrade, when xForwardedForProcessingMode is not set, the controller retains the existing configuration of the listener on ALB and does not start appending the X-Forwarded-For header field because of the component upgrade.

  • Use xForwardedForProcessingMode to control the X-Forwarded-For header field. This field takes precedence over xForwardedForEnabled.

apiVersion: alibabacloud.com/v1
kind: AlbInstance
metadata:
  name: alb-instance-example
  namespace: default
spec:
  listeners:
    - protocol: HTTPS
      port: 443
      xForwardedForConfig:
        xForwardedForProcessingMode: append   # Appends the client IP to X-Forwarded-For.
        xForwardedForProtoEnabled: true       # Obtains the listener protocol through the X-Forwarded-Proto header field.
        xForwardedForHostEnabled: true        # Obtains the domain name of the client request through the X-Forwarded-Host header field.
        xForwardedForSLBPortEnabled: true     # Obtains the ALB listener port through the X-Forwarded-Port header field.

Configure HTTPS mutual authentication

An HTTPS listener can enable mutual authentication through caEnabled and caCertificates, which requires the client to provide a certificate issued by the specified CA. First, upload the CA certificate to Alibaba Cloud Certificate Management Service, and then reference it by certificate ID. For information about how to obtain a root CA certificate, see Secure services with HTTPS mutual authentication.

apiVersion: alibabacloud.com/v1
kind: AlbInstance
metadata:
  name: alb-instance-example
  namespace: default
spec:
  listeners:
    - protocol: HTTPS
      port: 443
      caEnabled: true
      caCertificates:
        - certificateId: 123157xxxxx-cn-hangzhou   # Replace with the CA certificate ID.
Important
  • caCertificates declares the CA certificates associated with the listener as a complete list. When you add, delete, or replace a certificate ID in the list, the controller synchronously updates the ALB listener. The order of the list does not affect the result.

  • Mutual authentication is supported only on ALB standard editions. ALB extensible editions (GatewayClass alb-extensible) do not support mutual authentication yet. Do not configure caEnabled and caCertificates on listeners of the extensible edition.

Configure logging and tracing

Use logConfig to configure custom header recording in the access logs of a listener and Xtrace distributed tracing.

Important

Before you use the listener logConfig, first enable access logs for the instance through spec.config.accessLogConfig of AlbInstance. Otherwise, the listener update fails (AccessLogDisabled). Only ALB standard editions support the listener logConfig. Configuring this field on an ALB extensible edition causes the listener update to fail (OperationDenied.ResourceNotSupport).

apiVersion: alibabacloud.com/v1
kind: AlbInstance
metadata:
  name: alb-instance-example
  namespace: default
spec:
  listeners:
    - protocol: HTTP
      port: 80
      logConfig:
        accessLogRecordCustomizedHeadersEnabled: true   # Records custom headers in access logs.
        accessLogTracingConfig:
          tracingEnabled: true
          tracingType: Zipkin
          tracingSample: 100

Specify extended certificates (Certificate Management Service)

An HTTPS listener can reference Secret certificates through the Gateway tls.certificateRefs, or reference certificate IDs in Certificate Management Service through certificates of AlbInstance as extended certificates.

apiVersion: alibabacloud.com/v1
kind: AlbInstance
metadata:
  name: alb-instance-example
  namespace: default
spec:
  listeners:
    - protocol: HTTPS
      port: 443
      certificates:
        - certificateId: 123158xxxxx-cn-hangzhou   # Replace with the certificate ID.
The default certificate is the first Secret certificate in the Gateway tls.certificateRefs. When the Gateway does not reference a Secret certificate, the first certificate in certificates is used as the default certificate.
certificates : Duplicate certificate IDs in certificates are automatically deduplicated.

HTTPRoute configurations for multiple scenarios

Attach an HTTPRoute to multiple listeners at the same time

Declare multiple parent references in parentRefs to attach the same HTTPRoute to multiple listeners of the same Gateway. This configuration suits scenarios in which the same set of routing rules must take effect on multiple ports or multiple listeners at the same time, such as providing both HTTP and HTTPS access.

In the following example, demo-route-multi-listeners is attached to both the http80 and https443 listeners of the alb-test gateway. Requests whose hostname is demo.ingress.top or test.ingress.top and whose path is /api reach either of these two listeners and are then forwarded to the backend Service go-httpbin:80.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-multi-listeners
  namespace: default
spec:
  hostnames:
  - demo.ingress.top
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs:
    - group: ""
      kind: Service
      name: go-httpbin
      port: 80
      weight: 100
    matches:
    - path:
        type: Exact
        value: /api

Forward traffic to multiple backend Services by weight

In backendRefs, specify multiple backend Services and their weight values (the default value is 1 when it is not specified) to forward traffic to multiple backend Services by weight. In the example, the traffic ratio of the three Services is go-httpbin : coffee-svc : tea-svc = 1 : 2 : 3.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-multi-backendrefs
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs: # Multiple server groups
    - group: ""
      kind: Service
      name: go-httpbin
      port: 80
      weight: 1
    - group: ""
      kind: Service
      name: coffee-svc
      port: 80
      weight: 2
    - group: ""
      kind: Service
      name: tea-svc
      port: 80
      weight: 3
    matches:  
    - path:
        type: Exact  
        value: /api

Configure path matching rules

ALB standard editions (gatewayClassName: alb) support the following three path matching methods. ALB extensible editions (gatewayClassName: alb-extensible) do not support PathPrefix.

If an HTTPRoute rule does not explicitly configure matches or path, Gateway API adds the PathPrefix("/") matching rule by default. Because ALB extensible editions do not support PathPrefix, such default configurations are also rejected.

Matching method

Description

Example

PathPrefix

Prefix matching. Available only on ALB standard editions.

/api supports matching /api, /api/v1, /api/users, and more.

Exact

Exact match.

/healthz supports matching only /healthz.

RegularExpression

Regular expression matching.

/users/[0-9]+ supports matching /users/123, /users/456, and more.

The following example configures three different path matching methods for the same backend Service in one HTTPRoute: PathPrefix matches requests that start with /api, Exact performs an exact match on /healthz, and RegularExpression matches dynamic paths such as /users/5. Requests that meet any of the preceding matching conditions are forwarded to the backend Service go-httpbin:80.

When multiple matches are used, different matches are combined with OR. The rule matches if any one of them matches.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-path
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs: 
    - group: ""
      kind: Service
      name: go-httpbin
      port: 80
      weight: 1
    matches:  
    - path:
        type: PathPrefix 
        value: /api
    - path:
        type: Exact  
        value: /healthz
    - path:
        type: RegularExpression 
        value: /users/[0-9]+

Configure header matching

The following example uses the headers field to define a request header matching condition. The request is forwarded to the backend Service go-httpbin:80 only when it carries X-Custom-Header: my-value.

Header matching can be combined with other matching conditions. All conditions within the same match block must be satisfied (AND). Request header matching supports only the Exact match type.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-header
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs: 
    - group: ""
      kind: Service
      name: go-httpbin
      port: 80
      weight: 1
    matches:  
    - headers:  
      - name: X-Custom-Header
        type: Exact
        value: "my-value"

Add or remove request headers

Use the RequestHeaderModifier field to add or remove request headers before a request is forwarded to the backend Service.

add and set parameters both take a list of request header configurations, and each item contains a request header name and the corresponding value. The remove parameter takes a list of request header names.
  • add: Adds the specified request headers and their values.

  • set: Overwrites the specified request headers with the given values. If a request header already exists, its original value is replaced.

  • remove: Removes the specified request headers.

add, set, and remove are the three request header processing methods that the Gateway API community officially requires. In the design and implementation of ALB Gateway, add and set have the same semantics, so use the standard set semantics.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-header-modifier
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs: 
    - group: ""
      kind: Service
      name: go-httpbin
      port: 80
      weight: 1
    filters:
      - type: RequestHeaderModifier
        requestHeaderModifier:
          set:
            - name: X-Request-Id
              value: "X-Request-Id"
            - name: X-Test-Id
              value: "X-Test-Id"
          remove:
            - X-Legacy-Header
            - X-Test-Header
    matches:  
    - path:
        type: Exact 
        value: /api

Configure URLRewrite

The following example configures URLRewrite for an HTTPRoute through Gateway API. When a client accesses test.ingress.top/api, ALB, before forwarding the request to the backend Service go-httpbin:80, rewrites the request Host to test.internal and rewrites the path from /api to /v1/api.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-rewrite
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs: 
    - group: ""
      kind: Service
      name: go-httpbin
      port: 80
      weight: 1
    filters:
      - type: URLRewrite
        urlRewrite:
          hostname: test.internal
          path:
            type: ReplaceFullPath
            replaceFullPath: /v1/api
    matches:  
    - path:
        type: Exact 
        value: /api

Configure RequestRedirect

The following example configures RequestRedirect for an HTTPRoute through Gateway API. When a client accesses test.ingress.top/api, ALB no longer forwards the request to the backend Service, but directly returns a 301 redirect response. The client is redirected to https://new.example.com:443/new-path.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-redirect
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - filters:
      - type: RequestRedirect
        requestRedirect:
          scheme: https
          hostname: new.example.com
          port: 443
          statusCode: 301
          path:
            type: ReplaceFullPath
            replaceFullPath: /new-path
    matches:  
    - path:
        type: Exact 
        value: /api

Associate service extensions through ExtensionRef and AlbRule

ALB Gateway supports using the ExtensionRef filter of an HTTPRoute to reference AlbRule (a custom resource), which implements advanced forwarding rule configurations specific to ALB. Associating service extensions is the only supported advanced configuration.

Only ALB extensible editions (gatewayClassName: alb-extensible ) support associating service extensions through ExtensionRef and AlbRule.

The following requirements must be met when you configure this feature:

  • ExtensionRef.group must be alibabacloud.com, and kind must be AlbRule.

  • AlbRule must be in the same namespace as the HTTPRoute that references it.

  • AlbRule.spec.serviceExtensions is used to configure service extensions, and each element contains one serviceExtensionId.

  • serviceExtensionId corresponds to a service extension that was created in advance through the ALB console or API.

  • Each forwarding rule (that is, each match) can be associated with at most one service extension.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-extensionref
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs: 
    - group: ""
      kind: Service
      name: go-httpbin
      port: 80
      weight: 1
    filters:
      - type: ExtensionRef
        extensionRef:
          group: alibabacloud.com
          kind: AlbRule
          name: alb-rule-example
    matches:  
    - path:
        type: Exact 
        value: /api
---
apiVersion: alibabacloud.com/v1
kind: AlbRule
metadata:
  name: alb-rule-example
  namespace: default
spec:
  serviceExtensions:
    - serviceExtensionId: sen-sxq80j0gibopa9qes2 # Currently, each forwarding rule supports association with only one service extension

Forward traffic to backend Services across namespaces

When you forward traffic to a backend Service in a namespace different from the namespace of the HTTPRoute, you must create a ReferenceGrant in the target namespace to grant explicit authorization, so that access stays secure and controllable. With this mechanism, you can maintain routes centrally in the ingress namespace.

For example, the HTTPRoute is in the default namespace, and the backend Services are in the coffee and tea namespaces respectively. In addition to specifying backendRefs with the corresponding namespace, you must also create a ReferenceGrant in each of the coffee and tea namespaces.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-multi-namespace
  namespace: default
spec:
  hostnames:
  - test.ingress.top
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: http80
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: alb-test
    sectionName: https443
  rules:
  - backendRefs:
    - group: ""
      kind: Service
      name: coffee-svc
      namespace: coffee
      port: 80
      weight: 2
    - group: ""
      kind: Service
      name: tea-svc
      namespace: tea
      port: 80
      weight: 3
    matches:
    - path:
        type: Exact
        value: /api
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-default-httproute-to-coffee-service
  namespace: coffee
spec:
  from:
  - group: gateway.networking.k8s.io
    kind: HTTPRoute
    namespace: default
  to:
  - group: ""
    kind: Service
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-default-httproute-to-tea-service
  namespace: tea
spec:
  from:
  - group: gateway.networking.k8s.io
    kind: HTTPRoute
    namespace: default
  to:
  - group: ""
    kind: Service
---
apiVersion: v1
kind: Namespace
metadata:
  name: coffee
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coffee
  namespace: coffee
spec:
  replicas: 2
  selector:
    matchLabels:
      app: coffee
  template:
    metadata:
      labels:
        app: coffee
    spec:
      containers:
      - name: coffee
        image: registry.cn-hangzhou.aliyuncs.com/acs-sample/nginxdemos:latest
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: coffee-svc
  namespace: coffee
spec:
  ports:
  - port: 80
    targetPort: 80
    protocol: TCP
  selector:
    app: coffee
  type: ClusterIP
---
apiVersion: v1
kind: Namespace
metadata:
  name: tea
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tea
  namespace: tea
spec:
  replicas: 3
  selector:
    matchLabels:
      app: tea
  template:
    metadata:
      labels:
        app: tea
    spec:
      containers:
      - name: tea
        image: registry.cn-hangzhou.aliyuncs.com/acs-sample/nginxdemos:latest
        ports:
        - containerPort: 80
      readinessGates:
      - conditionType: target-health.alb.k8s.alibabacloud
---
apiVersion: v1
kind: Service
metadata:
  name: tea-svc
  namespace: tea
spec:
  ports:
  - port: 80
    targetPort: 80
    protocol: TCP
  selector:
    app: tea
  type: NodePort

Configure ALB server group properties through AlbServerGroup

AlbServerGroup is a Kubernetes CustomResourceDefinition (CRD) used to configure the properties of ALB server groups, such as health checks and service extensions.

Server group health checks

After you configure a health check for a backend Service, ALB periodically sends health check requests to the backend Service. If the response returned by the backend does not match the response codes defined in healthCheckCodes, the backend Service is marked as unhealthy. After a backend Service is marked as unhealthy, ALB automatically distributes new requests to other healthy backend servers. If the server group contains only unhealthy backend servers, ALB still routes requests to these servers to minimize business impact. For more information, see Configure and manage health checks.

apiVersion: alibabacloud.com/v1
kind: AlbServerGroup
metadata:
  name: sgc-coffee-healthcheck
  namespace: default
spec:
  targetRefs:
  - kind: Service
    name: coffee-svc
  default:
    healthCheckConfig:
      healthCheckEnabled: true
      healthCheckProtocol: HTTP
      healthCheckMethod: HEAD
      healthCheckPath: /healthz
      healthCheckHttpVersion: HTTP1.1
      healthCheckInterval: 10
      healthCheckTimeout: 5
      healthyThreshold: 3
      unhealthyThreshold: 3
      healthCheckCodes:
      - http_2xx

Associate a service extension with a server group

Associating a service extension through ExtensionRef and AlbRule associates the service extension with a forwarding rule, whereas this section associates a service extension with a server group.

Use serviceExtensions to associate the Service Extensions created in advance in the ALB console with a server group. Each server group can be associated with at most one service extension. Specifying multiple service extensions causes the configuration to fail.

Only ALB extensible editions support associating service extensions with server groups.
apiVersion: alibabacloud.com/v1
kind: AlbServerGroup
metadata:
  name: sgc-httpbin-extensions
  namespace: default
spec:
  targetRefs:
  - kind: Service
    name: go-httpbin
  default:
    serviceExtensions:
    - serviceExtensionId: sen-51d2l5npas0k7wg9yh