Thứ Tư, 29 tháng 4, 2026

GatewayAPI collection

https://oneuptime.com/blog/tag/gateway-api?page=4&pageSize=25
Contents
 
GatewayAPI  2
001. GatewayAPI - 1.Cài đặt bản std 2
001. GatewayAPI - 1.Cài đặt bản experimeltal  2
001. GatewayAPI - nginx từ HELM 3
001. Tạo GatewayClass 3
002. ingress2gateway  4
003. Tạo pod mẫu để test  4
TESTED-0: Create Gateway mới  4
TESTED-1 HttpRoute basic  5
TESTED-2: Tích hợp certmanager  5
TESTED-3: Multi Hostname và ssl - Basic 7
Ví dụ 4: Multi Hostname và ssl – ListenerSet  8
TESTED-5: Traffic Split 10
TESTED-6: Header Route  11
TESTED-7.1: Header Modify 12
TESTED-7.2: Header Modify - improve security  13
TESTED-8: Method+Path route 13
TESTED-9: Path route only 14
TESTED-10 Method Route only 15
TESTED-11: Query Parameter Route  15
TESTED-12: URL rewrite  16
TESTED-13: Mirror request 16
OK-12: ReferenceGrant: Cross NS HttpRoute->Services 17
OK-13: ReferenceGrant: Cross NS Gateway->Secret 18
OK-14: ReferenceGrant: Cross NS HttpRoute->Gateway  18
(NOT)Ví dụ 20: ReferenceGrant 19
TESTED-17: Increase timeout 19
TESTED-18: Redirect 301/302 20
(NOT)Ví dụ 8: TLS route 20
Ví dụ 16: TLS Passthought 20
Ví dụ 17: TLS Terminate 21
Ví dụ 18: Multi condition 21
(NOT)Ví dụ 19: TCP/UDP Route  21
Ví dụ 22: keepalived_timeout  21
Ví dụ 23: BackendTLSPolicy (Force trust)  22
(NOT)Ví dụ 24: CORS 22
(NOT)Ví dụ 26-A: mTLS Frontend  22
(NOT)Ví dụ 26-B: mTLS Backend 22
(NOT)Ví dụ 27: HTTP2.0 Support Backend  22
(NOT)Ví dụ 30: ListenerSet  22
Ví dụ 31: basic authen  22
Nginx GW Fabric Advance 22
SnippetsPolicies  22
ClientSettingsPolicy  22
UpstreamSettingsPolicy  23
Session-persistence 23
Authenticationfilters 23
Nginxgateways 23
nginxproxies  23
observabilitypolicies 23
proxysettingspolicies 23
ratelimitpolicies 23
snippetsfilters 23
upstreamsettingspolicies  23
Kiến trúc GWAPI 23
Security cho GatewayAPI 24
1. Giới hạn NS cho GW và httpRoute  24



GatewayAPI
001. GatewayAPI - 1.Cài đặt bản Standard
Tham khảo trong file cilium đã viết để cài đặt
Toàn bộ tài liệu https://gateway-api.sigs.k8s.io/guides/getting-started/
https://docs.nginx.com/nginx-gateway-fabric/get-started/#install-the-helm-chart
Kiểm tra bản mới nhất ở link này: https://gateway-api.sigs.k8s.io/guides/getting-started/introduction/
Bước 1: Cài CRD
wget https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.5.1/standard-install.yaml
k apply -f standard-install.yaml

Bước 2: Cài gatewayclass: nginx
Bản mới nhất ở đây https://docs.nginx.com/nginx-gateway-fabric/install/helm/#installing-the-gateway-api-resources

Kiểm tra độ tương thích trước khi cài version: https://github.com/nginx/nginx-gateway-fabric#technical-specifications
helm install ngf oci://ghcr.io/nginx/charts/nginx-gateway-fabric \
  --namespace nginx-gateway \
  --create-namespace \
  --version 2.6.2 \
  --wait

cat <<EOF > gatewayclass.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: nginx
spec:
  controllerName: gateway.nginx.org/nginx-gateway-controller
EOF

k apply -f gatewayclass.yaml
k get gatewayclasses.gateway.networking.k8s.io

001. GatewayAPI - 1.Cài đặt bản Experimeltal
Bước 1: Cài CRD với tính năng Experimental, thực chất bước này không cần cài nữa
Tìm bản mới nhất trên này https://gateway-api.sigs.k8s.io/guides/getting-started/introduction/  và trên này https://github.com/kubernetes-sigs/gateway-api/releases
wget https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.1/experimental-install.yaml
k apply --server-side -f experimental-install.yaml

root@cicd:~/install-gwapi# kubectl get crd | grep gateway.networking.k8s.io
backendtlspolicies.gateway.networking.k8s.io            2026-07-19T17:14:23Z
gatewayclasses.gateway.networking.k8s.io                2026-07-19T17:14:23Z
gateways.gateway.networking.k8s.io                      2026-07-19T17:14:24Z
grpcroutes.gateway.networking.k8s.io                    2026-07-19T17:14:24Z
httproutes.gateway.networking.k8s.io                    2026-07-19T17:14:24Z
listenersets.gateway.networking.k8s.io                  2026-07-19T17:14:24Z
referencegrants.gateway.networking.k8s.io               2026-07-19T17:14:24Z
tcproutes.gateway.networking.k8s.io                     2026-07-19T17:14:24Z
tlsroutes.gateway.networking.k8s.io                     2026-07-19T17:14:24Z
udproutes.gateway.networking.k8s.io                     2026-07-19T17:14:25Z

Bước 2: Cài Nginx gateway Fabric từ link
Bản cài chính thức, đã test: https://docs.nginx.com/nginx-gateway-fabric/install/manifests/open-source-experimental/
Link git của nó: https://github.com/nginx/nginx-gateway-fabric/tree/main/config/crd/gateway-api
kubectl kustomize "https://github.com/nginx/nginx-gateway-fabric/config/crd/gateway-api/experimental?ref=v2.6.7" | kubectl apply --server-side -f –

nếu gặp lỗi thì hãy xóa
kubectl delete crd tcproutes.gateway.networking.k8s.io
kubectl delete crd udproutes.gateway.networking.k8s.io

backendtlspolicies.gateway.networking.k8s.io
gatewayclasses.gateway.networking.k8s.io
gateways.gateway.networking.k8s.io
grpcroutes.gateway.networking.k8s.
httproutes.gateway.networking.k8s.
listenersets.gateway.networking.k8s.io
referencegrants.gateway.networking.k8s.io
tcproutes.gateway.networking.k8s.io
tlsroutes.gateway.networking.k8s.io
udproutes.gateway.networking.k8s.
xbackendtrafficpolicies.gateway.networking.x-k8s.io d
xmeshes.gateway.networking.x-k8s.io

Bước 3: Cài bổ xung CRD nâng cao rành riêng cho Nginx fabric
https://docs.nginx.com/nginx-gateway-fabric/install/manifests/open-source-experimental/#deploy-the-custom-resource-definitions
kubectl apply --server-side -f https://raw.githubusercontent.com/nginx/nginx-gateway-fabric/v2.6.7/deploy/crds.yaml
authenticationfilters.gateway.nginx.org
clientsettingspolicies.gateway.nginx.org
nginxgateways.gateway.nginx.org
nginxproxies.gateway.nginx.org serverside-applied
observabilitypolicies.gateway.nginx.org serverside-applied
proxysettingspolicies.gateway.nginx.org serverside-applied
ratelimitpolicies.gateway.nginx.org serverside-applied
snippetsfilters.gateway.nginx.org serverside-applied
snippetspolicies.gateway.nginx.org serverside-applied
upstreamsettingspolicies.gateway.nginx.org serverside-applied
wafpolicies.gateway.nginx.org serverside-applied
• authenticationfilters
• clientsettingspolicies
• nginxgateways
• nginxproxies
• observabilitypolicies
• proxysettingspolicies
• ratelimitpolicies
• snippetsfilters
• snippetspolicies
• upstreamsettingspolicies

Bước 4: Cài đặt deployment
wget  https://raw.githubusercontent.com/nginx/nginx-gateway-fabric/v2.6.7/deploy/experimental/deploy.yaml
vim deploy.yaml, dòng cuối
# NHỚ ĐỔI TỪ LOCAL-> CLUSTER cho svc, để vào được web
externalTrafficPolicy: Cluster

k apply -f deploy.yaml




001. GatewayAPI - nginx từ HELM
Bản mới nhất đây https://docs.nginx.com/nginx-gateway-fabric/install/helm/#installing-the-gateway-api-resources
Kiểm tra phiên bản: https://github.com/nginx/nginx-gateway-fabric/pkgs/container/charts%2Fnginx-gateway-fabric/versions?filters%5Bversion_type%5D=tagged
Kiểm tra độ tương thích trước khi cài version: https://github.com/nginx/nginx-gateway-fabric#technical-specifications
helm pull oci://ghcr.io/nginx/charts/nginx-gateway-fabric --version 0.0.0-edge
tar –xvzf
cd nginx-gateway-fabric
helm install ngf . \
  --namespace nginx-gateway \
  --create-namespace \
  --wait
001. Tạo GatewayClass
cat <<EOF > gatewayclass.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
  name: nginx
spec:
  controllerName: gateway.nginx.org/nginx-gateway-controller
EOF

k apply -f gatewayclass.yaml
k get gatewayclasses.gateway.networking.k8s.io

Để xem GatewayAPI hỗ trợ những chức năng nào, ta như sau
# k get gatewayclasses.gateway.networking.k8s.io nginx -o yaml
 

002. ingress2gateway
wget https://github.com/kubernetes-sigs/ingress2gateway/releases/download/v1.0.0/ingress2gateway_Linux_x86_64.tar.gz
ingress2gateway print --providers=ingress-nginx --all-namespaces > gateway-api-manifests.yaml
ingress2gateway print --providers=ingress-nginx --input-file=./ingress1.yaml

003. Tạo pod mẫu để test
k create ns app-namespace1
k create ns app-namespace2
k -n app-namespace1 create deployment web1 --image=traefik/whoami --replicas=1 -- --name="Web1 tuantest"
k -n app-namespace1 expose deployment web1 --name=svc-web1 --port=80 --target-port=80 --type=ClusterIP
k -n app-namespace1 create deployment web1a --image=traefik/whoami --replicas=1
k -n app-namespace1 expose deployment web1a --name=svc-web1a --port=80 --target-port=80 --type=ClusterIP
k -n app-namespace1 create deployment web1b --image=traefik/whoami --replicas=1
k -n app-namespace1 expose deployment web1b --name=svc-web1b --port=80 --target-port=80 --type=ClusterIP
k -n app-namespace2 create deployment web2 --image=traefik/whoami --replicas=1
k -n app-namespace2 expose deployment web2 --name=svc-web2 --port=80 --target-port=80 --type=ClusterIP

TESTED-0: Create Gateway mới
https://gateway-api.sigs.k8s.io/guides/getting-started/simple-gateway/
***Chú ý: thể tạo nhiều gateway, mỗi gw sẽ 1 ip LB riêng

k create ns production-gateway
k create ns fronend-app

openssl req -x509 -nodes -days 365 -newkey rsa:2048   -keyout tls.key   -out tls.crt   -subj "/CN=default-gateway/O=Default Certificate"
kubectl create secret tls default-cert --key tls.key   --cert tls.crt   -n frontend-app

cat << EOF > 01.simple-gateway.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: my-gateway
  namespace: production-gateway
spec:
  gatewayClassName: nginx
  listeners:
  - name: http
    protocol: HTTP
    port: 80
    allowedRoutes:
      namespaces:
        from: All
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - name: default-cert #chú ý phải có tạo secret ở trên
    allowedRoutes:
      namespaces:
        from: All
EOF

k apply -f 01.simple-gateway.yaml

TESTED-1 HttpRoute basic
cat << EOF > 01.simple-httproute.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: app-http
  namespace: app-namespace1
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /v1/api  #có thể để thành / nếu muốn route all traffic.
    backendRefs:
    - name: svc-web1 #chú ý trùng tên svc
      port: 80
EOF

k apply -f 01.simple-httproute.yaml

curl -v http://test.tuan.name.vn/v1/api


TESTED-2: Tích hợp certmanager
Xem mục chính CertManager, cài như bình thường
https://freedium-mirror.cfd/https://faun.pub/kubernetes-gateway-api-a-complete-step-by-step-setup-guide-397d0ff5375f
https://docs.nginx.com/nginx-gateway-fabric/traffic-security/integrate-cert-manager/
*** Chú ý Tuấn: đây ta phải tạo Certificate.yaml mới, sau đó mới add vào gateway
cat << EOF > 02.certmanager-certificate.yaml
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: test-tuan-name-vn-tls
  namespace: nginx-gateway
spec:
  secretName: test-tuan-name-vn-tls-secret
  duration: 2160h # 90 ngày
  renewBefore: 360h # Tự Gia hạn trước khi hết hạn 15 ngày (360 giờ)
  issuerRef:
    name: letsencrypt-stag
    kind: ClusterIssuer
  commonName: test.tuan.name.vn
  dnsNames: #có hỗ trợ multi ssl trên cùng 1 ssl file
  - test.tuan.name.vn
EOF


cat << EOF > 02.certmanager-gateway.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: my-gateway
  namespace: nginx-gateway
  annotations:
    # Tùy chọn: Một số controller dùng annotation này để tự động map cert
    cert-manager.io/cluster-issuer: letsencrypt-stag
spec:
  gatewayClassName: nginx
  listeners:
  - name: http
    protocol: HTTP
    port: 80
    allowedRoutes:
      namespaces:
        from: All
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - name: default-cert
    allowedRoutes:
      namespaces:
        from: All
  - name: https-test-tuan-name-vn
    protocol: HTTPS
    port: 443
    hostname: "test.tuan.name.vn"
    tls:
      mode: Terminate
      certificateRefs:
      - name: test-tuan-name-vn-tls-secret
    allowedRoutes:
      namespaces:
        from: All
EOF

cat << EOF > 02.certmanager-httproute.yaml
# HTTP
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: app-web1-http-redirect
  namespace: app-namespace1
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - filters:
    - type: RequestRedirect
      requestRedirect:
        scheme: https
        statusCode: 302 # Chuyển hướng tạm thời 302 sang 443
---
# HTTPS
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: app-web1-https-route
  namespace: app-namespace1
spec:
  parentRefs:
  - name:  my-gateway
    namespace: nginx-gateway
    sectionName: https-test-tuan-name-vn # Khớp với 'name' của listener 443 trong Gateway
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /
    backendRefs:
    - name: svc-web1 #chú ý trùng tên svc
      port: 80
EOF
Kết quả:
curl -v http://test.tuan.name.vn
#< HTTP/1.1 302 Moved Temporarily
#< Location: https://test.tuan.name.vn/

curl -v https://test.tuan.name.vn
#*  subject: CN=test.tuan.name.vn
#*  start date: May  1 16:43:03 2026 GMT
#*  expire date: Jul 30 16:43:02 2026 GMT
#*  issuer: C=US; O=(STAGING) Let's Encrypt; CN=(STAGING) Tenuous Tomato R13



TESTED-3: Multi Hostname và ssl - Basic
openssl req -x509 -nodes -days 365 -newkey rsa:2048   -keyout tls1.key   -out tls1.crt   -subj "/CN=*.domain1.com/O=Default Certificate"
kubectl create secret tls default-cert-domain1 --key tls1.key   --cert tls1.crt   -n nginx-gateway

openssl req -x509 -nodes -days 365 -newkey rsa:2048   -keyout tls2.key   -out tls2.crt   -subj "/CN=*.domain2.com/O=Default Certificate"
kubectl create secret tls default-cert-domain2 --key tls2.key   --cert tls2.crt   -n nginx-gateway

openssl req -x509 -nodes -days 365 -newkey rsa:2048   -keyout tls.key   -out tls.crt   -subj "/CN=default-gateway/O=Default Certificate"
kubectl create secret tls default-cert --key tls.key   --cert tls.crt   -n nginx-gateway


k create ns app-namespace1
k create ns app-namespace2

cat << EOF > 03.multi-wildcard.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: wildcard-gateway
  namespace: nginx-gateway
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  gatewayClassName: nginx
  listeners:
  - name: http
    protocol: HTTP
    port: 80 # Đây là default
    allowedRoutes:
      namespaces:
        from: All
  - name: https
    protocol: HTTPS
    port: 443 # Đây là default
    tls:
      mode: Terminate
      certificateRefs:
      - name: default-cert
    allowedRoutes:
      namespaces:
        from: All
  - name: https-wildcard-domain1
    protocol: HTTPS
    port: 443
    hostname: "*.domain1.com"
    tls:
      mode: Terminate
      certificateRefs:
      - name: default-cert-domain1
    allowedRoutes:
      namespaces:
        from: All
  - name: https-wildcard-domain2
    protocol: HTTPS
    port: 443
    hostname: "*.domain2.com"
    tls:
      mode: Terminate
      certificateRefs:
      - name: default-cert-domain2
    allowedRoutes:
      namespaces:
        from: All
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: app1-domain1-route
  namespace: app-namespace1
spec:
  parentRefs:
  - name: wildcard-gateway
    namespace: nginx-gateway
    sectionName: https-wildcard-domain1 # Gắn đúng vào listener của domain1
  hostnames:
  - "app1.domain1.com" # Chỉ định subdomain cụ thể
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /
    backendRefs:
    - name: svc-web1
      port: 80
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: app22-domain1-route
  namespace: app-namespace2
spec:
  parentRefs:
  - name: wildcard-gateway
    namespace: nginx-gateway
    sectionName: https-wildcard-domain2 # Gắn đúng vào listener của domain1
  hostnames:
  - "app2.domain2.com" # Chỉ định subdomain cụ thể
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /
    backendRefs:
    - name: svc-web2
      port: 80
EOF


k apply -f 03.multi-wildcard.yaml



curl -vk https://app1.domain1.com
*  subject: CN=*.domain1.com; O=Default Certificate
*  start date: Jul 19 21:16:12 2026 GMT
*  expire date: Jul 19 21:16:12 2027 GMT

curl -vk https://app2.domain2.com
*  subject: CN=*.domain2.com; O=Default Certificate
*  start date: Jul 19 21:16:12 2026 GMT
*  expire date: Jul 19 21:16:12 2027 GMT




TESTED-4: ListenerSet
https://gateway-api.sigs.k8s.io/guides/user-guides/listener-set/
Cách tiếp cận này giúp bạn giải quyết 2 vấn đề lớn:
• Phân quyền (Self-service): Đội Platform chỉ cần quản lý 1 Gateway dùng chung. Từng đội phát triển ứng dụng ở các namespace khác nhau tự tạo ListenerSet để cài đặt domain và SSL của riêng họ.
• Vượt giới hạn: Giúp cluster phá vỡ giới hạn cứng 64 listeners trên một Gateway duy nhất của Kubernetes.
 


k create ns team-1-ns
k create ns team-2-ns
k create ns infra-gateway

kubectl create deployment team-1-app -n team-1-ns --image=traefik/whoami --port=80
kubectl expose deployment team-1-app -n team-1-ns --name=team-1-service --port=80 --target-port=80

kubectl create deployment team-2-app -n team-2-ns --image=traefik/whoami --port=80
kubectl expose deployment team-2-app -n team-2-ns --name=team-2-service --port=80 --target-port=80

openssl req -x509 -nodes -days 365 -newkey rsa:2048   -keyout tls3.key   -out tls3.crt   -subj "/CN=*.first.foo.com/O=Default Certificate"
kubectl create secret tls first-workload-cert --key tls3.key   --cert tls3.crt  -n team-1-ns

openssl req -x509 -nodes -days 365 -newkey rsa:2048   -keyout tls4.key   -out tls4.crt   -subj "/CN=*.second.foo.com/O=Default Certificate"
kubectl create secret tls second-workload-cert --key tls4.key   --cert tls4.crt  -n team-2-ns

cat << EOF > 04.listerner-set.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-gateway
  namespace: infra-gateway
spec:
  gatewayClassName: nginx
  allowedListeners:
    namespaces:
      from: All
  listeners:
  - name: foo
    hostname: foo.com
    protocol: HTTP
    port: 80
---
apiVersion: gateway.networking.k8s.io/v1
kind: ListenerSet
metadata:
  name: first-workload-listeners
  namespace: team-1-ns
spec:
  parentRef:
    namespace: infra-gateway
    name: shared-gateway
    kind: Gateway
    group: gateway.networking.k8s.io
  listeners:
  - name: first
    hostname: "*.first.foo.com"
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - kind: Secret
        group: ""
        name: first-workload-cert
---
apiVersion: gateway.networking.k8s.io/v1
kind: ListenerSet
metadata:
  name: second-workload-listeners
  namespace: team-2-ns
spec:
  parentRef:
    namespace: infra-gateway
    name: shared-gateway
    kind: Gateway
    group: gateway.networking.k8s.io
  listeners:
  - name: second
    hostname: "*.second.foo.com"
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - kind: Secret
        group: ""
        name: second-workload-cert
EOF

k apply -f 04.listerner-set.yaml
sleep 10
k get gateway -A
k get listenersets.gateway.networking.k8s.io -A

cat << EOF > 041.httproute.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: team-1-route
  namespace: team-1-ns # Đặt cùng namespace với ListenerSet của Team 1
spec:
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: ListenerSet # <--- Bắt buộc chỉ định là ListenerSet thay vì Gateway
    name: first-workload-listeners # Tên của ListenerSet tương ứng
    sectionName: first # Tên listener bên trong ListenerSet đó
  hostnames:
  - "*.first.foo.com"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /
    backendRefs:
    - name: team-1-service # Service backend nằm trong team-1-ns
      port: 80
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: team-2-route
  namespace: team-2-ns # Đặt cùng namespace với ListenerSet của Team 2
spec:
  parentRefs:
  - group: gateway.networking.k8s.io
    kind: ListenerSet # <--- Chỉ định ListenerSet làm cha
    name: second-workload-listeners
    sectionName: second
  hostnames:
  - "*.second.foo.com"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /
    backendRefs:
    - name: team-2-service # Service backend nằm trong team-2-ns
      port: 80
EOF

k apply -f 041.httproute.yaml

curl -vk --resolve test.first.foo.com:443:192.168.88.151 https://test.first.foo.com
*  start date: Jul 21 14:46:20 2026 GMT
*  expire date: Jul 21 14:46:20 2027 GMT
*  issuer: CN=*.first.foo.com; O=Default Certificate

Xóa rác sau khi test
k delete ns infra-gateway ; k delete ns team-1-ns ; k delete ns team-2-ns


TESTED-5: Traffic Split
https://gateway-api.sigs.k8s.io/guides/traffic-splitting/
cat << EOF > 05.traffic-splitting-httproute.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-split
  namespace: app-namespace1
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /test5
    backendRefs:
    - name: svc-web1  #đây là svc1 của pod1
      port: 80
      weight: 90
    - name: svc-web1a  #đây là svc2 của pod1
      port: 80
      weight: 10
EOF

k apply -f 05.traffic-splitting-httproute.yaml

curl http://test.tuan.name.vn/test5

# Run multiple requests
for i in {1..20}; do
  curl -s http://test.tuan.name.vn/test5 | grep Hostname;
done

k delete -f 05.traffic-splitting.yaml

nên ưu tiên chia traffic như tỉ lệ sau
 

TESTED-6: Header Route
https://gateway-api.sigs.k8s.io/guides/traffic-splitting/#canary-traffic-rollout
cat << EOF > 06.traffic-splitting-header-route.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-headers
  namespace: app-namespace1
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /test6
      headers:
      - name: version #vị trí header nằm ở đây version=v2
        value: v2
    backendRefs:
    - name: svc-web1a
      port: 80
  - matches:
    - path:
        type: PathPrefix
        value: /test6
    backendRefs:
    - name: svc-web1
      port: 80
EOF

k apply -f 06.traffic-splitting-header-route.yaml

# Default request goes to v1
curl test.tuan.name.vn/test6
Hostname: web1-888886b4d-tg4jv
# Request with header goes to v2
curl -H "version: v2" test.tuan.name.vn/test6
Hostname: web1-888886b4d-t6rbg
 

Ví dụ khác về header route
https://oneuptime.com/blog/post/2026-02-09-httproute-traffic-routing/view
# httproute-headers.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: header-routing
  namespace: default
spec:
  parentRefs:
    - name: http-gateway
  hostnames:
    - "example.com"
  rules:
    # Route mobile users to mobile backend
    - matches:
        - headers:
            - name: User-Agent
              type: RegularExpression
              value: ".*(Mobile|Android|iPhone).*"
      backendRefs:
        - name: mobile-service
          port: 8080

    # Route beta users to canary backend
    - matches:
        - headers:
            - name: X-Beta-User
              type: Exact
              value: "true"
      backendRefs:
        - name: canary-service
          port: 8080

    # Default backend
    - matches:
        - path:
            type: PathPrefix
            value: "/"
      backendRefs:
        - name: stable-service
          port: 8080


TESTED-7.1: Header Modify
https://gateway-api.sigs.k8s.io/guides/http-header-modifier/
cat << EOF > 07.http-header-modifier.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: header-manipulation-route
  namespace: app-namespace1 # Namespace chứa ứng dụng của bạn
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /test7
    # 🛠️ CẤU HÌNH THAO TÁC VỚI HEADER NẰM Ở ĐÂY
    filters:
    # 1. Thao tác với REQUEST HEADERS (Gửi từ Client -> Backend)
    - type: RequestHeaderModifier
      requestHeaderModifier:
        # Thêm header mới (Nếu đã tồn tại sẽ bị ghi đè)
        set:
        - name: X-Environment-Type
          value: "Production"
        # Cộng dồn thêm giá trị vào header đã có
        add:
        - name: X-Forwarded-For-Custom
          value: "nginx-fabric-gateway"
        # Xóa bỏ header nhạy cảm trước khi đẩy vào Backend
        remove:
        - "X-Internal-Secret"
        - "Authorization-Debug"
    # 2. Thao tác với RESPONSE HEADERS (Trả từ Backend -> Client)
    - type: ResponseHeaderModifier
      responseHeaderModifier:
        # Thêm header chuẩn bảo mật cho Client
        set:
        - name: Strict-Transport-Security
          value: "max-age=999999; includeSubDomains"
        - name: X-Frame-Options
          value: "DENY"
        # Thêm thông tin định danh hệ thống
        add:
        - name: Server-Trace
          value: "gateway-node-01xxxx"
        # Ẩn bớt các header lộ thông tin hệ thống backend
        remove:
        - "X-Powered-By"
        - "X-AspNet-Version"
    backendRefs:
    - name: svc-web1
      port: 80
EOF

k apply -f 07.http-header-modifier.yaml


curl -vk http://test.tuan.name.vn/test7
< Server-Trace: gateway-node-01xxxx
< Strict-Transport-Security: max-age=999999; includeSubDomains


TESTED-7.2: Header Modify - improve security
https://oneuptime.com/blog/post/2026-02-09-gateway-tls-certificate-refs/view#security-best-practices
# secure-headers-route.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: secure-headers
spec:
  parentRefs:
  - name: tls-gateway
  rules:
  - filters:
    - type: ResponseHeaderModifier
      responseHeaderModifier:
        add:
        - name: Strict-Transport-Security
          value: "max-age=31536000; includeSubDomains"
        - name: X-Content-Type-Options
          value: "nosniff"
        - name: X-Frame-Options
          value: "DENY"
    backendRefs:
    - name: app-service
      port: 8080


TESTED-8: Method+Path route

https://gateway-api.sigs.k8s.io/guides/http-method-matching/
• A POST request to /v8/api will be routed to infra-backend-v1.
• A GET request to /v8/api will be routed to infra-backend-v2.

cat << EOF > 08.http-method-matching.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: method-and-path-matching
  namespace: app-namespace1
spec:
  parentRefs:
  - name: my-gateway
    namespace: nginx-gateway
    sectionName: http
  hostnames:
  - "test.tuan.name.vn"
  rules:
  # Quy tắc 1: Phải là POST VÀ đường dẫn bắt đầu bằng /v8/api
  - matches:
    - path:
        type: PathPrefix
        value: /v8/api
      method: POST
    backendRefs:
    - name: svc-web1
      port: 80

  # Quy tắc 2: Phải là GET VÀ đường dẫn bắt đầu bằng /v8/api
  - matches:
    - path:
        type: PathPrefix
        value: /v8/api
      method: GET
    backendRefs:
    - name: svc-web1a
      port: 80
EOF
Kiểm tra
curl -XGET test.tuan.name.vn/v8/api
Hostname: web1a-d5f6f44bf-nzl4d

curl -XPOST test.tuan.name.vn/v8/api
Hostname: web1-84c9884bbb-7mmb8

k delete -f 08.http-method-matching.yaml


TESTED-9: Path route only

cat << EOF > 09.path-route-only.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: demo-route-paths
  namespace: app-namespace1 # Namespace chứa ứng dụng của bạn
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /v1a
    backendRefs:
    - name: svc-web1a
      port: 80
  - matches:
    - path:
        type: PathPrefix
        value: /
    backendRefs:
    - name: svc-web1
      port: 80
EOF
Kiểm tra
curl test.tuan.name.vn
curl test.tuan.name.vn/v1a

k delete -f 09.path-route-only.yaml

TESTED-10 Method Route only
cat << EOF > 10.method-route-only.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: method-matching
  namespace: app-namespace1 # Namespace chứa ứng dụng của bạn
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
  - matches:
    - method: POST
    backendRefs:
    - name: svc-web1
      port: 80
  - matches:
    - method: GET
    backendRefs:
    - name: svc-web1a
      port: 80
EOF

k apply -f 10.method-route-only.yaml


k delete -f 10.method-route-only.yaml




TESTED-11: Query Parameter Route
https://gateway-api.sigs.k8s.io/guides/http-query-param-matching/
cat << EOF > 11.httproute-query-params.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: query-routing
  namespace: app-namespace1 # Namespace chứa ứng dụng của bạn
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
    # Route debug requests to debug backend
    - matches:
        - queryParams:
            - name: debug
              type: Exact
              value: "true"
      backendRefs:
        - name: svc-web1a
          port: 80

    # Route specific API versions
    - matches:
        - queryParams:
            - name: api_version
              type: Exact
              value: "2.0"
      backendRefs:
        - name: svc-web1b
          port: 80

    # Default routing
    - backendRefs:
        - name: svc-web1
          port: 80

EOF
Kiểm tra
Nguyên lý
grep -r 'api_version' /etc/nginx/conf.d/matches.json
{"1_0":[{"redirectPath":"/_ngf-internal-rule0-route0","params":["debug=Exact=true"]},{"redirectPath":"/_ngf-internal-rule0-route1","params":["api_version=Exact=2.0"]},{"redirectPath":"/_ngf-internal-rule0-route2","any":true}]}

curl test.tuan.name.vn/v1a?debug=true
curl test.tuan.name.vn/v1a?debug=api_version=2.0

k delete -f 11.httproute-query-params.yaml


TESTED-12: URL rewrite
cat << EOF > 12.httproute-url-rewrite.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: url-rewrite
  namespace: app-namespace1 # Namespace chứa ứng dụng của bạn
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
    # Rewrite /v1/api/* to /api/*
    - matches:
        - path:
            type: PathPrefix
            value: "/v1/api"
      filters:
        - type: URLRewrite
          urlRewrite:
            path:
              type: ReplacePrefixMatch
              replacePrefixMatch: "/api"
      backendRefs:
        - name: svc-web1
          port: 80

    # Rewrite /old-path to /new-path
    - matches:
        - path:
            type: PathPrefix
            value: "/old-path"
      filters:
        - type: URLRewrite
          urlRewrite:
            path:
              type: ReplaceFullPath
              replaceFullPath: "/new-path"
      backendRefs:
        - name: svc-web1
          port: 80
EOF
Kiểm tra
curl test.tuan.name.vn/v1/api/111
#Hostname: web1-888886b4d-tg4jv
#GET /api/111 HTTP/1.1
curl test.tuan.name.vn/old-path
#Hostname: web1-888886b4d-tg4jv
#GET /new-path HTTP/1.1

k delete -f 12.httproute-url-rewrite.yaml


TESTED-13: Mirror request
https://gateway-api.sigs.k8s.io/guides/http-request-mirroring/
https://docs.nginx.com/nginx-gateway-fabric/traffic-management/mirror/

k -n app-namespace1 expose deployment nginx --name=svc-nginx --port=80 --target-port=80 --type=ClusterIP
k -n app-namespace1 create deployment nginx --image=nginx:alpine

cat << EOF > 13.httproute-mirroring.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: traffic-mirroring
  namespace: app-namespace1
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: "/api"
      backendRefs:
        # Primary backend main pod
        - name: svc-web1
          port: 80

      filters:
        # Mirror to debug-pod
        - type: RequestMirror
          requestMirror:
            backendRef:
              name: svc-nginx
              port: 80
EOF
Kiểm tra
curl test.tuan.name.vn/api
curl test.tuan.name.vn/api
curl test.tuan.name.vn/api
k -n app-namespace1  logs nginx-7977cdf8f5-czbkj

k delete -f 13.httproute-mirroring.yaml
k -n app-namespace1 delete deployment nginx
k -n app-namespace1 delete svc svc-nginx

OK-12: ReferenceGrant: Cross namespace for HttpRoute->Services
https://oneuptime.com/blog/post/2026-02-09-gateway-api-referencegrant-cross-namespace/view
Kịch bản là tạo HTTPRoute với 1 số /path đặc biệt: từ namespace  AAA nhưng lại trỏ vào SVC của namespace BBB. Ta cần khai báo ReferenceGrant
# httproute-cross-namespace.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: cross-namespace-route
  namespace: frontend-namespace
spec:
  parentRefs:
    - name: shared-gateway
      namespace: gateway-namespace
  hostnames:
    - "example.com"
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: "/api"
      backendRefs:
        - name: api-service
          namespace: backend-namespace
          port: 8080

---
# ReferenceGrant allowing cross-namespace reference
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-frontend-to-backend
  namespace: backend-namespace
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: frontend-namespace
  to:
    - group: ""
      kind: Service
      name: api-service

OK-13: ReferenceGrant: Cross namespace for Gateway->Secret
https://oneuptime.com/blog/post/2026-02-09-gateway-api-referencegrant-cross-namespace/view
https://gateway-api.sigs.k8s.io/guides/tls/#cross-namespace-certificate-references
# Certificate in certs namespace
apiVersion: v1
kind: Secret
metadata:
  name: shared-tls-cert
  namespace: certs
type: kubernetes.io/tls
data:
  tls.crt: <base64-cert>
  tls.key: <base64-key>
---
# Grant access from infrastructure namespace
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-gateway-to-certs
  namespace: certs
spec:
  from:
  - group: gateway.networking.k8s.io
    kind: Gateway
    namespace: infrastructure
  to:
  - group: ""
    kind: Secret
    name: shared-tls-cert
---
# Gateway in infrastructure namespace
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: cross-ns-gateway
  namespace: infrastructure
spec:
  gatewayClassName: kong
  listeners:
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - kind: Secret
        name: shared-tls-cert
        namespace: certs  # Cross-namespace reference
    allowedRoutes:
      namespaces:
        from: All

OK-14: ReferenceGrant: Cross namespace HttpRoute->Gateway
https://oneuptime.com/blog/post/2026-02-09-gateway-api-referencegrant-cross-namespace/view
trường hợp này sử dụng khi gateway chưa setting allowedRoutes.namespcae.from=All
# Gateway in shared infrastructure namespace

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-gateway
  namespace: gateway-system
spec:
  gatewayClassName: nginx
  listeners:
  - name: http
    protocol: HTTP
    port: 80
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - kind: Secret
        name: default-tls
        namespace: certificates
---
# Allow tenant-a to use the gateway
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-tenant-a
  namespace: gateway-system
spec:
  from:
  - group: gateway.networking.k8s.io
    kind: HTTPRoute
    namespace: tenant-a
  to:
  - group: gateway.networking.k8s.io
    kind: Gateway
    name: shared-gateway
---
# Tenant-a HTTPRoute
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: tenant-a-route
  namespace: tenant-a
spec:
  parentRefs:
  - kind: Gateway
    name: shared-gateway
    namespace: gateway-system  # Cross-namespace reference
  hostnames:
  - "app.tenant-a.example.com"
  rules:
  - backendRefs:
    - kind: Service
      name: app-service
      port: 80
OK-15 ReferenceGrant: Cross namespace ListenerSet->Secret
Tương tự giống Gateway đọc Secret
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-teams-to-access-certs
  namespace: xxxx # <--- PHẢI đặt tại Namespace CHỨA tài nguyên đích (Secret)
spec:
  from:
  - group: gateway.networking.k8s.io
    kind: ListenerSet
    namespace: yyyy # <--- PHẢI đặt tại Namespace CHỨA ListenerSet
  - group: gateway.networking.k8s.io
    kind: ListenerSet
    namespace: zzzz # <--- PHẢI đặt tại Namespace CHỨA ListenerSet
  to:
  - group: ""
    kind: Secret               # Tài nguyên được phép truy cập chéo

(NOT)Ví dụ 20: ReferenceGrant
https://oneuptime.com/blog/post/2026-02-09-gateway-api-referencegrant-cross-namespace/view
https://oneuptime.com/blog/post/2026-02-09-cross-namespace-referencegrant/view#multi-tenant-gateway-architecture


TESTED-17: Increase timeout
All of timeout Gateway Api https://oneuptime.com/blog/post/2026-02-09-httproute-timeout-policies/view#graceful-timeout-handling

cat << EOF > 17.httproute-timeouts.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: timeout-configuration
  namespace: app-namespace1 # Namespace chứa ứng dụng của bạn
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn"
  rules:
    # Fast endpoints with short timeout
    - matches:
        - path:
            type: PathPrefix
            value: "/health"
      timeouts:
        request: "5s"
        backendRequest: "3s"
      backendRefs:
        - name: svc-web1
          port: 80

    # Slow endpoints with longer timeout
    - matches:
        - path:
            type: PathPrefix
            value: "/reports"
      timeouts:
        request: "60s"
        backendRequest: "55s"
      backendRefs:
        - name: svc-web1
          port: 80
EOF
Chạy oke nhưng chưa biết test, để sau đi

TESTED-18: Redirect 301/302
cat << EOF > 18.httproute-redirect.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: redirect-example
  namespace: app-namespace1 # Namespace chứa ứng dụng của bạn
spec:
  parentRefs:
  - name: my-gateway #chú ý trùng tên gateway
    namespace: nginx-gateway
    sectionName: http #chú ý trùng tên section
  hostnames:
  - "test.tuan.name.vn" #Ta có thể bỏ hostnames để redirect https cho toàn bộ GW
  rules:
    # Redirect to new domain
    - filters:
        - type: RequestRedirect
          requestRedirect:
            hostname: new.example.com
            statusCode: 302
            scheme: https
EOF
Kết qu
curl -vk http://test.tuan.name.vn
< HTTP/1.1 301 Moved Permanently
< Location: https://new.example.com/


(NOT)Ví dụ 8: TLS route
https://oneuptime.com/blog/post/2026-02-09-tlsroute-passthrough/view
https://gateway-api.sigs.k8s.io/guides/tls-routing/


Ví dụ 16: TLS Passthought
https://oneuptime.com/blog/post/2026-02-09-gateway-api-tlsroute-passthrough-tls/view
Cách hoạt động: Gateway hoàn toàn không giải mã dữ liệu. Nó chỉ đọc trường SNI (Server Name Indication) trong thông điệp TLS ClientHello của client để biết request muốn gửi tới domain nào, sau đó chuyển tiếp nguyên vẹn luồng traffic đã mã hóa xuống backend.
• Yêu cầu: Việc giải mã TLS và quản lý chứng chỉ hoàn toàn do chính dịch vụ backend đảm nhận. Tầng Gateway điều hướng bằng tài nguyên TLSRoute thay vì HTTPRoute.
Tiêu chí  TLS Passthrough (Chuyển tiếp) TLS Termination (Chấm dứt)
Bảo mật Bảo mật End-to-End tuyệt đối. Khóa bí mật nằm tại Pod ứng dụng, không bị lộ ra tầng Gateway chung.  Tập trung khóa bí mật tại Gateway. Nếu Gateway bị tấn công, toàn bộ traffic của các ứng dụng có thể bị lộ.
Quản lý Cert  Phân tán: Các đội phát triển tự quản lý chứng chỉ trên từng ứng dụng của họ.  Tập trung: Đội hạ tầng quản lý toàn bộ chứng chỉ tại Gateway.
Hiệu năng Rất cao & Độ trễ thấp: Gateway không tốn tài nguyên CPU để giải mã/mã hóa lại dữ liệu.  Tốn tài nguyên CPU của Gateway để xử lý quá trình bắt tay (handshake) và giải mã liên tục.
Khả năng Định tuyến Hạn chế: Chỉ có thể định tuyến dựa trên tên miền (SNI). Không thể đọc Header, Path (/api), hay Cookie.  Linh hoạt (Layer 7): Có thể định tuyến nâng cao dựa vào Cookie, HTTP Headers, Method, hoặc các đường dẫn cụ thể.
An toàn (WAF/Ghi log) Kém: Gateway không thể kiểm tra mã độc hay áp dụng luật bảo mật WAF do dữ liệu bị mã hóa hoàn toàn. Tốt: Dễ dàng ghi log chi tiết URL, kiểm tra các lỗ hổng bảo mật trực tiếp tại tầng Gateway.


# passthrough-gateway.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: passthrough-gateway
spec:
  gatewayClassName: kong
  listeners:
  - name: tls-passthrough
    protocol: TLS
    port: 443
    tls:
      mode: Passthrough  # No termination, forward encrypted
    allowedRoutes:
      kinds:
      - kind: TLSRoute
      namespaces:
        from: All
---
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TLSRoute
metadata:
  name: passthrough-route
spec:
  parentRefs:
  - name: passthrough-gateway
  hostnames:
  - "secure.example.com"
  rules:
  - backendRefs:
    - name: secure-backend
      port: 443
Ví dụ 17: TLS Terminate
Giống với ví dụ 3

Ví dụ 18: Multi condition
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: complex-matching
spec:
  parentRefs:
  - name: production-gateway
  hostnames:
  - "api.example.com"
  rules:
  # Match requires ALL conditions to be true
  - matches:
    - path:
        type: PathPrefix
        value: /api
      headers:
      - type: Exact
        name: X-API-Key
        value: secret-key
      queryParams:
      - type: Exact
        name: format
        value: json
    backendRefs:
    - name: authenticated-api
      port: 8080

(NOT)Ví dụ 19: TCP/UDP Route
https://oneuptime.com/blog/post/2026-02-09-gateway-api-tcproute-udproute-layer4/view
https://gateway-api.sigs.k8s.io/guides/tcp/

# tcp-gateway.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: tcp-gateway
  namespace: infra-gateway
spec:
  gatewayClassName: nginx
  listeners:
  # PostgreSQL listener
  - name: postgres
    protocol: TCP
    port: 5432
    allowedRoutes:
      kinds:
      - kind: TCPRoute
  # Redis listener
  - name: redis
    protocol: TCP
    port: 6379
    allowedRoutes:
      kinds:
      - kind: TCPRoute
  # MySQL listener
  - name: mysql
    protocol: TCP
    port: 3306
    allowedRoutes:
      kinds:
      - kind: TCPRoute

# k get svc -A | grep tcp-gateway
infra-gateway    tcp-gateway-nginx                 LoadBalancer   10.100.61.191    192.168.88.151   3306:30128/TCP,5432:30337/TCP,6379:31344/TCP   9m4s

# k get pod -A | grep tcp-gateway
infra-gateway     tcp-gateway-nginx-768c99d865-9jpm8         1/1     Running   0                9m9s

Tạo pod và svc
# postgres-tcproute.yaml
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TCPRoute
metadata:
  name: postgres-route
  namespace: database
spec:
  parentRefs:
  - name: tcp-gateway
    sectionName: postgres  # Reference the postgres listener
    namespace: infra-gateway
  rules:
  - backendRefs:
    - name: postgres-service
      port: 5432
---
apiVersion: v1
kind: Service
metadata:
  name: postgres-service
  namespace: database
spec:
  selector:
    app: postgres
  ports:
  - name: postgres
    protocol: TCP
    port: 5432
    targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  namespace: database
spec:
  serviceName: postgres-service
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:15-alpine
        ports:
        - containerPort: 5432
        env:
        - name: POSTGRES_PASSWORD
          value: changeme
        - name: POSTGRES_DB
          value: myapp





Ví dụ 22: keepalived_timeout
https://gateway-api.sigs.k8s.io/guides/http-timeouts/
Thay vì dùng chung một biến keepalive_timeout như Nginx truyền thống, Gateway API chia timeout thành hai cấp độ chính trong tài nguyên HTTPRoute:
• Request Timeout (request): Tổng thời gian tối đa để toàn bộ vòng đời của một request kết thúc (từ lúc Gateway nhận đến lúc gửi xong phản hồi cuối cùng cho client).
• Backend Timeout (backendRequest): Thời gian chờ tối đa cho một phản hồi từ backend phục vụ (upstream) sau khi request đã được gửi đi.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: my-route
spec:
  rules:
  - timeouts:
      request: 10s           # Tổng thời gian request tối đa
      backendRequest: 2s     # Thời gian chờ Backend phản hồi (tương tự proxy_read_timeout)
    backendRefs:
    - name: my-service
      port: 80

Ví dụ 23: BackendTLSPolicy (Force trust)
https://gateway-api.sigs.k8s.io/api-types/backendtlspolicy/#:~:text=are%20not%20allowed.-,WellKnownCACertificates,of%20choice%20for%20more%20information.

https://gateway-api.sigs.k8s.io/guides/tls/#using-system-certificates
apiVersion: gateway.networking.k8s.io/v1alpha3
kind: BackendTLSPolicy
metadata:
  name: secure-backend-policy
  namespace: my-app-namespace  # <--- Namespace của bạn ở đây
spec:
  targetRefs:
    - group: ""
      kind: Service
      name: my-backend-service
      # Lưu ý: BackendTLSPolicy chỉ có hiệu lực cho Service
      # nằm trong cùng namespace với chính nó.
  validation:
    hostname: xxx.example.com
    wellKnownCACertificates: System

(NOT)Ví dụ 24: CORS
https://gateway-api.sigs.k8s.io/guides/http-cors/
https://docs.nginx.com/nginx-gateway-fabric/traffic-security/cors/


Cần nghiên cứu thêm

(NOT)Ví dụ 26-A: mTLS Frontend
https://gateway-api.sigs.k8s.io/guides/tls/#basic-client-validation
https://docs.nginx.com/nginx-gateway-fabric/traffic-security/client-validation/

(NOT)Ví dụ 26-B: mTLS Backend
https://docs.nginx.com/nginx-gateway-fabric/traffic-security/secure-backend/


(NOT)Ví dụ 27: HTTP2.0 Support Backend
https://gateway-api.sigs.k8s.io/guides/backend-protocol/



Ví dụ 31: basic authen
https://docs.nginx.com/nginx-gateway-fabric/traffic-security/basic-authentication/
https://docs.nginx.com/nginx-gateway-fabric/traffic-security/integrate-cert-manager/

Nginx GW Fabric Advance

SnippetsPolicies
https://docs.nginx.com/nginx-gateway-fabric/traffic-management/snippets/

ClientSettingsPolicy
https://docs.nginx.com/nginx-gateway-fabric/traffic-management/client-settings/
• client_max_body_size
• client_body_timeout
• keepalive_requests
• keepalive_time
• keepalive_timeout
• keepalive_min_timeout




UpstreamSettingsPolicy
https://docs.nginx.com/nginx-gateway-fabric/traffic-management/upstream-settings/


Session-persistence
https://docs.nginx.com/nginx-gateway-fabric/traffic-management/session-persistence/
Tương đương ip-hash để giữ phiên client connect đến backend

Authenticationfilters

Nginxgateways

nginxproxies

observabilitypolicies

proxysettingspolicies

ratelimitpolicies

snippetsfilters

upstreamsettingspolicies


Kiến trúc GWAPI
 
 
 

Security cho GatewayAPI
1. Giới hạn NS cho GW và httpRoute
Không Nên nên
   
 



GatewayAPI collection

https://oneuptime.com/blog/tag/gateway-api?page=4&pageSize=25 Contents   GatewayAPI  2 001. GatewayAPI - 1.Cài đặt bản std 2 001. Gatewa...