Bài trước dừng ở những giới hạn của Ingress. Gateway API là câu trả lời của chính SIG Network: bộ API mới giàu tính năng hơn, chuẩn hóa những thứ trước đây phải dùng annotation, và chia rõ ai sở hữu phần nào. Trong bài này bạn cài Gateway API và Envoy Gateway lên cluster hoc-k8s, đưa notes-api ra ngoài qua notes.localtest.me, thử rewrite và redirect, rồi chạy canary 90/10 giữa notes-api 1.0 và 1.1.
Gateway API (nhóm gateway.networking.k8s.io) đạt GA từ bản v1.0 năm 2023 và là hướng được khuyến nghị cho cluster mới. So với Ingress:
Nhớ lại Compose: một người viết toàn bộ nginx.conf cho mọi service. Ở công ty lớn thường có team platform vận hành proxy, chứng chỉ, IP công khai, và nhiều team ứng dụng chỉ muốn khai báo "đường dẫn của tôi vào service của tôi". Gateway API mô hình hóa đúng sự phân công đó.
| Tài nguyên | Phạm vi | Ai sở hữu | Tương đương thời Ingress |
|---|---|---|---|
| GatewayClass | Cluster | Nhà cung cấp hạ tầng (cloud, team cài implementation) | IngressClass |
| Gateway | Namespace | Cluster operator | Pod + Service LoadBalancer của controller, phần TLS của Ingress |
| HTTPRoute và các Route khác | Namespace | Developer ứng dụng | Phần rules của Ingress |
spec.controllerName.LoadBalancer cho nó.HTTPRoute chỉ được nhận khi cả hai phía đồng ý:
spec.parentRefs trỏ tới Gateway, có thể kèm sectionName để chọn một listener. parentRefs[].namespace bỏ trống nghĩa là cùng namespace với route.allowedRoutes.namespaces.from: Same (mặc định, chỉ namespace của Gateway), All (mọi namespace) hoặc Selector (namespace có label khớp).*.localtest.me nhận route có hostname notes.localtest.me, không nhận route chỉ có api.example.com. Khác Ingress, wildcard của Gateway API khớp một hoặc nhiều nhãn: *.localtest.me khớp cả a.b.localtest.me, nhưng không khớp localtest.me.Team platform giữ quyền quyết định namespace nào được cắm vào gateway công khai; team ứng dụng tự sửa route mà không đụng tới Gateway.
Envoy Gateway là implementation Gateway API của dự án Envoy. Controller của nó watch các đối tượng Gateway API; với mỗi Gateway, nó tạo Deployment chạy proxy Envoy cùng Service LoadBalancer, rồi đẩy cấu hình định tuyến xuống Envoy qua giao thức xDS. Envoy gửi request thẳng tới IP Pod lấy từ EndpointSlice.
hoc-k8s; namespace notes có Postgres, Redis, Deployment notes-api (3 bản, notes-api:1.0) và Service notes-api (80 → 3000) từ chương 4 và 5.helm: ở đây chỉ dùng như trình cài đặt (chương 12 học kỹ), cài theo hướng dẫn trên helm.sh.cloud-provider-kind: cấp IP cho Service LoadBalancer trên kind.go install sigs.k8s.io/cloud-provider-kind@latest # hoặc: brew install cloud-provider-kindChạy trong một terminal riêng và để nguyên suốt chương:
cloud-provider-kind --gateway-channel disabledcloud-provider-kind đóng vai "nhà cung cấp cloud" cho kind: thấy Service type: LoadBalancer là dựng một load balancer (container trên mạng Docker kind) và ghi IP vào status.loadBalancer. Bản gần đây còn kèm một implementation Gateway API nhỏ, bật mặc định; --gateway-channel disabled tắt nó để Envoy Gateway là implementation duy nhất, giống cluster production.
NOTE
Trên Linux, IP load balancer (dạng 172.18.0.x) truy cập được trực tiếp. Trên macOS và Windows (WSL2), mạng Docker không định tuyến tới máy host: chạy sudo cloud-provider-kind --gateway-channel disabled --enable-lb-port-mapping (Windows: terminal "Run as administrator"), hoặc dùng cách port-forward ở cuối Bước 5.
Gateway API phát hành theo hai kênh (channel): standard chỉ gồm tài nguyên và trường đã ổn định; experimental thêm tính năng đang thử, có thể đổi không tương thích. Production nên dùng standard.
Chọn phiên bản: lấy bản Envoy Gateway mới nhất ở trang releases (github.com/envoyproxy/gateway/releases), rồi tra bảng tương thích (compatibility matrix) trong tài liệu Envoy Gateway để biết bản Gateway API đi kèm. Giá trị dưới đây đúng lúc viết bài, hãy kiểm tra lại:
export EG_VERSION=v1.10.0
export GATEWAY_API_VERSION=v1.6.1
kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/${GATEWAY_API_VERSION}/standard-install.yaml
kubectl get crd | grep gateway.networking.k8s.iogatewayclasses.gateway.networking.k8s.io 2026-11-28T09:12:03Z
gateways.gateway.networking.k8s.io 2026-11-28T09:12:03Z
grpcroutes.gateway.networking.k8s.io 2026-11-28T09:12:03Z
httproutes.gateway.networking.k8s.io 2026-11-28T09:12:03Z
referencegrants.gateway.networking.k8s.io 2026-11-28T09:12:03Z
...--server-side cần thiết vì các CRD này rất lớn, vượt giới hạn annotation last-applied-configuration của apply phía client. Lúc này cluster đã hiểu kind Gateway, HTTPRoute… nhưng chưa ai thực thi chúng, giống Ingress không có controller.
# CRD riêng của Envoy Gateway (gateway.envoyproxy.io), không cài lại CRD Gateway API
helm template eg-crds oci://docker.io/envoyproxy/gateway-crds-helm --version ${EG_VERSION} \
--set crds.gatewayAPI.enabled=false \
--set crds.envoyGateway.enabled=true \
| kubectl apply --server-side -f -
# Controller; crds.enabled=false vì CRD đã có
helm install eg oci://docker.io/envoyproxy/gateway-helm --version ${EG_VERSION}
deployment.apps/envoy-gateway condition metWARNING
Quickstart của Envoy Gateway dùng helm install không có --set crds.enabled=false: lệnh đó tự cài luôn CRD Gateway API kênh experimental. Cách đó cũng chạy, nhưng đừng trộn hai cách trong một cluster: các bản Gateway API mới kèm một ValidatingAdmissionPolicy chặn cài CRD experimental đè lên CRD standard. Chỉ để một nguồn quản lý CRD.
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: eg
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controllerapiVersion: v1
kind: Namespace
metadata:
name: gateway-infra
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: shared-gateway
namespace: gateway-infra
spec:
gatewayClassName
Listener http nhận HTTP cổng 80 cho mọi host *.localtest.me, chỉ từ namespace có label shared-gateway-access: "true". Gắn label cho notes là việc của operator:
kubectl apply -f gatewayclass.yaml -f gateway.yaml
kubectl label namespace notes shared-gateway-access=true
kubectl get gatewayclass
kubectl -n gateway-infra get gatewayNAME CONTROLLER ACCEPTED AGE
eg gateway.envoyproxy.io/gatewayclass-controller True 15s
NAME CLASS ADDRESS PROGRAMMED AGE
shared-gateway eg 172.18.0.6 True 15sACCEPTED True: Envoy Gateway đã nhận GatewayClass. PROGRAMMED True kèm ADDRESS: proxy đã chạy và có IP. Xem Service mà Envoy Gateway dựng giúp bạn:
kubectl -n envoy-gateway-system get svc -l gateway.envoyproxy.io/owning-gateway-name=shared-gatewayNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
envoy-gateway-infra-shared-gateway-6f1d2c8a LoadBalancer 10.96.201.45 172.18.0.6 80:31872/TCP 40sNếu ADDRESS trống và PROGRAMMED là False, gần như chắc chắn cloud-provider-kind chưa chạy: Service đang <pending>.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: notes-api
namespace: notes
spec:
parentRefs:
- name: shared-gateway
namespace: gateway-infra
sectionName: http
hostnames
backendRefs[].port là cổng của Service (80), không phải cổng container (3000).
kubectl apply -f notes-api-route.yaml
kubectl -n notes get httproute
export GATEWAY_IP=$(kubectl -n gateway-infra get gateway shared-gateway -o jsonpath='{.status.addresses[0].value}')
curl -s --resolve notes.localtest.me:80:${GATEWAY_IP} http://notes.localtest.me/health; echo
curl -s
httproute.gateway.networking.k8s.io/notes-api created
NAME HOSTNAMES AGE
notes-api ["notes.localtest.me"] 3s
{"status":"ok"}
{"status":"ok"}
404--resolve giữ URL có tên miền; -H "Host: ..." gọi thẳng IP và tự đặt header. Host shop.localtest.me khớp listener nhưng không route nào nhận, nên Envoy trả 404.
TIP
Cách dự phòng chạy được mọi nơi (macOS, Windows, hoặc khi Gateway chưa có IP): port-forward tới Service của Envoy, rồi dùng --connect-to của curl thay cho --resolve. --connect-to bảo curl kết nối tới 127.0.0.1:8080 nhưng vẫn coi URL là http://notes.localtest.me/.
export ENVOY_SERVICE=$(kubectl -n envoy-gateway-system get svc \
-l gateway.envoyproxy.io/owning-gateway-namespace=gateway-infra,gateway.envoyproxy.io/owning-gateway-name=shared-gateway \
-o jsonpath='{.items[0].metadata.name}')
kubectl -n envoy-gateway-system port-forward service/${ENVOY_SERVICE} 8080:80
# terminal khác:
curl -s --connect-to notes.localtest.me:80:127.0.0.1:8080 http://notes.localtest.me/healthGateway API ghi trạng thái vào từng route, theo từng Gateway cha:
kubectl -n notes get httproute notes-api -o yamlstatus:
parents:
- parentRef:
group: gateway.networking.k8s.io
kind: Gateway
name: shared-gateway
namespace: gateway-infra
sectionName: http
controllerName: gateway.envoyproxy.io/gatewayclass-controller
conditions:
- type
backendRefs có tồn tại và được phép không.Thử làm hỏng có chủ đích: gỡ label của namespace notes.
kubectl label namespace notes shared-gateway-access-
kubectl -n notes get httproute notes-api -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
curl -s -o /dev/null -w "%{http_code}\n" --resolve notes.localtest.me:80:${GATEWAY_IP} http://notes.localtest.me/health
kubectl label namespace notes shared-gateway-access=truenamespace/notes unlabeled
Accepted=False (NotAllowedByListeners)
ResolvedRefs=True (ResolvedRefs)
404
namespace/notes labeled| Condition | reason | Ý nghĩa, cách sửa |
|---|---|---|
| Accepted=False | NotAllowedByListeners | allowedRoutes không cho namespace này (mặc định là Same) |
| Accepted=False | NoMatchingListenerHostname | Hostname của route không giao với hostname listener nào |
| Accepted=False | NoMatchingParent | sectionName/port trong parentRefs không khớp listener nào |
| ResolvedRefs=False | BackendNotFound | Service không tồn tại, sai tên hoặc sai cổng |
| ResolvedRefs=False | RefNotPermitted | Trỏ tới Service namespace khác mà không có ReferenceGrant |
| ResolvedRefs=False | InvalidKind | backendRefs trỏ tới kind không được hỗ trợ |
Route không có status.parents nào thường nghĩa là không controller nào nhận nó: sai tên hoặc namespace Gateway trong parentRefs, hoặc GatewayClass không ai phụ trách.
Mỗi rule gồm matches (điều kiện), filters (biến đổi) và backendRefs (đích):
| Loại khớp | Ví dụ | Ghi chú |
|---|---|---|
path PathPrefix | value: /api | Theo phần tử đường dẫn: khớp /api, /api/x, không khớp /apix |
path Exact | value: /health | Nguyên chuỗi |
path RegularExpression | value: ^/v[0-9]+/ | Cú pháp regex tùy implementation |
headers | name: X-Canary, value: "true" | Mặc định type: Exact; tên header không phân biệt hoa thường |
queryParams | name: canary, value: "1" | Mặc định type: Exact |
method | method: POST | GET, POST, PUT… |
Các điều kiện trong cùng một phần tử của matches kết hợp bằng VÀ; nhiều phần tử trong matches là HOẶC. Không ghi path thì mặc định PathPrefix /.
Khi nhiều rule (kể cả ở nhiều HTTPRoute) cùng khớp, chuẩn quy định thứ tự ưu tiên: hostname cụ thể thắng wildcard; rồi path Exact; rồi prefix dài hơn; rồi có khớp method; rồi nhiều điều kiện header hơn; rồi nhiều điều kiện query hơn. Vẫn hòa thì route tạo sớm hơn thắng, rồi theo thứ tự chữ cái namespace/name, rồi rule đứng trước. Bài tập ngay sau bài này cho bạn tự cài đặt phần cốt lõi của thuật toán đó.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: notes-api
namespace: notes
spec:
parentRefs:
- name: shared-gateway
namespace: gateway-infra
sectionName: http
hostnames
kubectl apply -f notes-api-route.yaml
curl -s --resolve notes.localtest.me:80:${GATEWAY_IP} http://notes.localtest.me/api/health; echo
curl -si --resolve notes.localtest.me:80:${GATEWAY_IP} http://notes.localtest.me/healthz | grep -iE "^(HTTP|location)"{"status":"ok"}
HTTP/1.1 301 Moved Permanently
location: http://notes.localtest.me/healthReplacePrefixMatch: /: /api/health thành /health trước khi tới notes-api, ứng dụng không cần biết tiền tố /api. Rewrite được cả hostname.location, request không tới backend (nên rule này không có backendRefs). Đổi được scheme, hostname, port, path; bài HTTPS tự động với cert-manager dùng nó để ép HTTP sang HTTPS.set, add, remove header gửi tới backend (notes-api không in header nên bạn không thấy trực tiếp). Ngoài ra còn ResponseHeaderModifier, RequestMirror (nhân bản request sang backend khác để thử) và ở các bản mới có CORS.Ở bài Rolling update, rollback và chiến lược triển khai, canary dựa vào tỷ lệ số Pod dưới cùng một Service. Gateway API chính xác hơn: hai Service, chia theo trọng số request, không phụ thuộc số Pod.
kind load docker-image notes-api:1.1 --name hoc-k8s # nếu chưa nạp ở chương 4
kubectl -n notes get deploy notes-api -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'notes-api:1.0Nếu ra notes-api:1.1, đưa về bằng kubectl -n notes set image deploy/notes-api notes-api=notes-api:1.0.
apiVersion: apps/v1
kind: Deployment
metadata:
name: notes-api-canary
namespace: notes
labels:
app: notes-api-canary
spec:
replicas: 1
selector:
matchLabels:
app
Label app: notes-api-canary khác app: notes-api, nên Pod canary không lọt vào Service notes-api: mỗi Service chứa đúng một phiên bản.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: notes-api
namespace: notes
spec:
parentRefs:
- name: shared-gateway
namespace: gateway-infra
sectionName: http
hostnames
kubectl apply -f notes-api-canary.yaml
kubectl -n notes rollout status deploy/notes-api-canary
kubectl apply -f notes-api-route-canary.yaml
for i in $(seq 1 200); do
curl -s --resolve notes.localtest.me:80:${GATEWAY_IP} http://notes.localtest.me/health; echo
done 181 {"status":"ok"}
19 {"status":"ok","version":"1.1"}Khoảng 10% vào 1.1 dù bản cũ có 3 Pod còn canary chỉ 1. Dùng chung Service như chương 4, tỷ lệ sẽ là 1/4 = 25%. Trọng số là tương đối (90/10 như 9/1); weight: 0 là không nhận traffic.
curl -s -H "X-Canary: true" --resolve notes.localtest.me:80:${GATEWAY_IP} http://notes.localtest.me/health; echo
curl -s --resolve notes.localtest.me:80:${GATEWAY_IP} "http://notes.localtest.me/health?canary=1"; echo{"status":"ok","version":"1.1"}
{"status":"ok","version":"1.1"}Rule header/query thắng rule / vì cùng path mặc định PathPrefix / nhưng có thêm điều kiện. Quy trình thật: nâng dần 90/10 → 50/50 → 0/100 bằng cách sửa weight, theo dõi lỗi (chương 13); yên tâm rồi thì cập nhật Deployment notes-api lên 1.1 và bỏ canary. Trong lab, chỉ dọn canary để giữ notes-api 1.0 cho các chương sau:
kubectl apply -f notes-api-route.yaml
kubectl delete -f notes-api-canary.yamlTeam frontend ở namespace web (đã được gắn label shared-gateway-access=true) muốn gửi /notes thẳng tới Service notes-api ở namespace notes:
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: web
namespace: web
spec:
parentRefs:
- name: shared-gateway
namespace: gateway-infra
hostnames:
- www.localtest.me
Chỉ vậy thì route có ResolvedRefs=False, reason RefNotPermitted: một namespace không được tự ý trỏ vào tài nguyên của namespace khác. Chủ namespace đích phải cấp phép bằng ReferenceGrant:
apiVersion: gateway.networking.k8s.io/v1
kind: ReferenceGrant
metadata:
name: allow-web-routes
namespace: notes # đặt ở namespace ĐÍCH
spec:
from:
- group: gateway.networking.k8s.io
kind: HTTPRoute
namespace: web
parentRefs sang Gateway namespace khác không cần ReferenceGrant: phía Gateway đã kiểm soát bằng allowedRoutes.v1 từ Gateway API v1.5; cluster có CRD cũ hơn dùng gateway.networking.k8s.io/v1beta1.Các bản Gateway API gần đây lần lượt đưa TLSRoute, rồi TCPRoute và UDPRoute lên kênh standard; mức hỗ trợ tùy implementation, xem trang conformance của từng dự án.
Envoy Gateway chỉ là một lựa chọn. NGINX Gateway Fabric, Traefik, Cilium, Istio, Kong, Contour và Gateway của các dịch vụ Kubernetes trên cloud đều triển khai cùng API: đổi implementation chủ yếu là đổi gatewayClassName, HTTPRoute giữ nguyên. Tính năng ngoài chuẩn (rate limit, xác thực JWT, retry nâng cao) được gắn qua policy riêng của implementation (với Envoy Gateway là các CRD như BackendTrafficPolicy, SecurityPolicy) thay vì annotation.
1. no matches for kind "HTTPRoute" in version "gateway.networking.k8s.io/v1": CRD chưa cài. Gateway API không có sẵn trong Kubernetes.
2. Gateway PROGRAMMED False, ADDRESS trống: cloud-provider-kind chưa chạy (Service LoadBalancer <pending>), hoặc GatewayClass chưa ACCEPTED vì sai controllerName.
3. Route Accepted=False (NotAllowedByListeners): quên rằng allowedRoutes mặc định là Same, hoặc quên gắn label cho namespace.
4. ResolvedRefs=False (BackendNotFound): ghi port: 3000 (cổng container) thay vì cổng Service 80, hoặc sai tên Service.
5. Route không có status: parentRefs thiếu namespace nên trỏ nhầm vào namespace của route, hoặc sai tên Gateway.
6. Hai route giành cùng host và path: route tạo sớm hơn thắng, route kia "im lặng" không nhận traffic. Quy ước mỗi hostname do một team, một HTTPRoute quản lý.
7. Trộn CRD standard và experimental: cài CRD từ nhiều nguồn (release manifest, chart của implementation) dễ xung đột phiên bản. Chọn một nguồn.
gateway.networking.k8s.io/v1) là thế hệ kế tiếp của Ingress: biểu đạt nhiều hơn trong chuẩn, chuyển được giữa implementation, cài dưới dạng CRD theo kênh standard/experimental.allowedRoutes); developer → HTTPRoute.parentRefs phía route, allowedRoutes (mặc định Same) và hostname giao nhau phía listener.matches (path PathPrefix/Exact, headers, queryParams, method; VÀ trong một phần tử, HOẶC giữa các phần tử), filters (RequestHeaderModifier, RequestRedirect, URLRewrite…), backendRefs có weight để canary theo request.Accepted và ResolvedRefs kèm reason cụ thể.--resolve hoặc port-forward + --connect-to.
Comments