Sau bài trước, TaskFlow API đã chạy ổn định với probe, requests và limits, nhưng vẫn chỉ gọi được từ trong cụm hoặc qua port-forward. Bài này mình sẽ giới thiệu với mọi người cách đưa ứng dụng ra ngoài với Gateway API: Ingress và sự kết thúc của ingress-nginx, các resource của Gateway API, cài Traefik trên kind, rồi viết Gateway, HTTPRoute để gọi TaskFlow bằng http://taskflow.local:8080. Bài dùng lại cụm taskflow ở trạng thái cuối Bài 16.
1. Vì sao không mở NodePort cho từng Service?
Ở Bài 11 chúng ta đã đưa Service ra ngoài bằng NodePort và thấy LoadBalancer đứng ở <pending> trên kind. Làm vậy cho từng Service thì sớm gặp vấn đề:
- NodePort là port lạ (30000–32767), mỗi Service một port cần mở firewall; LoadBalancer trên cloud là một load balancer thật, một IP và một khoản phí cho mỗi Service.
- Cả hai chỉ làm việc ở tầng TCP: không đọc được hostname hay path của request HTTP, nên không chia được
/apivà/docscho hai Service khác nhau, cũng không có chỗ chung để gắn HTTPS.
Cách làm phổ biến là một reverse proxy làm cổng vào duy nhất: chỉ proxy được mở ra ngoài, nó đọc request HTTP rồi chuyển tới đúng Service theo hostname và path, giống Caddy trong bài reverse proxy của series Docker, nhưng cấu hình bằng resource Kubernetes.
2. Ingress, ingress-nginx và Gateway API.
Resource đầu tiên cho việc này là Ingress. Các bạn sẽ còn gặp nó ở nhiều hệ thống đang chạy, nên mình để một ví dụ để nhận ra (chỉ đọc, không apply):
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: taskflow-api
namespace: taskflow
annotations:
nginx.ingress.kubernetes.io/proxy-body-size: 10m
spec:
ingressClassName: nginx
rules:
- host: taskflow.local
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: taskflow-api
port:
number: 80
Ingress chỉ mô tả được host, path và TLS. Mọi thứ khác (giới hạn body, timeout, rewrite, chia traffic) phải nhét vào annotation riêng của từng controller như dòng nginx.ingress.kubernetes.io/...: đổi controller là viết lại annotation. Docs Kubernetes ghi rõ API Ingress đã bị đóng băng (frozen): vẫn chạy nhưng không thêm tính năng.
Controller Ingress phổ biến nhất là ingress-nginx. Tháng 11/2025, SIG Network và Security Response Committee của Kubernetes thông báo cho ingress-nginx nghỉ hưu: chỉ bảo trì cầm chừng tới tháng 3/2026, sau đó không còn bản phát hành, không sửa lỗi, kể cả lỗ hổng bảo mật; cụm đang chạy không hỏng ngay nhưng nên chuyển sang Gateway API. Vì vậy series dạy Gateway API làm cách chính.
Gateway API là bộ API chính thức (nhóm
gateway.networking.k8s.io) thay thế Ingress, tách cấu hình cổng vào thành nhiều resource theo vai trò của người quản lý.
GatewayClass(cấp cụm, do nhà cung cấp hạ tầng quản lý): một loại cổng vào, chỉ ra controller nào xử lý, tương tựingressClassName.Gateway(do người vận hành cụm quản lý): một cổng vào cụ thể gồm các listener (port, giao thức, hostname, TLS) và namespace nào được gắn route vào.HTTPRoute(do dev ứng dụng quản lý): luật khớp hostname, path, header rồi gửi tới Service, kèm filter như rewrite, đổi header, chia traffic theo trọng số. Ngoài ra cònGRPCRoute,TLSRoute,TCPRoute,UDPRoute.
Những thứ Ingress phải nhờ annotation thì Gateway API viết thẳng trong spec, nên manifest chuyển được giữa các implementation. Kubernetes không tự xử lý Gateway API: cụm cần một implementation (controller cộng proxy). Bản mới nhất là v1.7.0 (29/10/2026).
3. Chọn Traefik và cài lên kind.
Trong danh sách implementation, mình chọn Traefik v3.8 vì:
- Traefik v3.8.0 (23/11/2026) dùng Gateway API v1.7.0 và đã chạy conformance cho bản này; Envoy Gateway, lựa chọn mạnh còn lại, bản mới nhất v1.10 vẫn ở Gateway API v1.6.1.
- Nhẹ: một Pod vừa là controller vừa là proxy, đo trên cụm khoảng 45Mi RAM. Envoy Gateway chạy controller riêng cộng một Deployment Envoy cho mỗi Gateway, muốn NodePort phải viết thêm resource
EnvoyProxy. - Cài được bằng manifest và
kubectl apply, chưa cần Helm (Bài 23). k3s, thứ chúng ta dùng cho cụm VPS ở Bài 31, cài sẵn Traefik và CRD Gateway API.
Cài CRD của Gateway API
Gateway API không có sẵn trong Kubernetes mà được cài thêm dưới dạng CRD (CustomResourceDefinition, cách thêm loại resource mới vào API). Mình cài kênh standard (ổn định) v1.7.0; kênh experimental chứa các tính năng đang thử:
kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.7.0/standard-install.yaml
# customresourcedefinition.apiextensions.k8s.io/backendtlspolicies.gateway.networking.k8s.io serverside-applied
# customresourcedefinition.apiextensions.k8s.io/gatewayclasses.gateway.networking.k8s.io serverside-applied
# customresourcedefinition.apiextensions.k8s.io/gateways.gateway.networking.k8s.io serverside-applied
# ...
# validatingadmissionpolicybinding.admissionregistration.k8s.io/safe-upgrades.gateway.networking.k8s.io serverside-applied
Dùng --server-side như docs của Gateway API vì CRD rất lớn (riêng HTTPRoute hơn 400 KB), apply kiểu thường sẽ chép cả file vào annotation last-applied-configuration (Bài 7), vượt giới hạn 256 KB. kubectl api-resources --api-group=gateway.networking.k8s.io giờ liệt kê 10 loại resource mới.
Cài Traefik
Phần hạ tầng không thuộc ứng dụng nên mình để trong thư mục riêng platform/traefik/, tách khỏi k8s/. Đầu tiên là quyền đọc resource Gateway API và ghi status, lấy từ file RBAC của Traefik, đổi namespace của ServiceAccount sang traefik (RBAC học ở Bài 27):
mkdir -p platform/traefik
curl -sSL https://raw.githubusercontent.com/traefik/traefik/v3.8/docs/content/reference/dynamic-configuration/kubernetes-gateway-rbac.yml | sed 's/namespace: default/namespace: traefik/' > platform/traefik/rbac.yaml
Phần còn lại gồm Namespace traefik, ServiceAccount traefik-controller, GatewayClass, Deployment và Service:
- platform/traefik/traefik.yaml (lược bớt)
# ... Namespace traefik, ServiceAccount traefik-controller
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: traefik
# ... label
spec:
# Gateway nào dùng class này thì do Traefik xử lý
controllerName: traefik.io/gateway-controller
---
# ... Deployment traefik, 1 replica, serviceAccountName: traefik-controller
- name: traefik
image: traefik:v3.8.0
args:
# entryPoint web: listener của Gateway phải dùng đúng port 8000 này
- --entryPoints.web.address=:8000
# entryPoint nội bộ cho /ping (probe)
- --entryPoints.traefik.address=:8080
- --ping=true
# đọc GatewayClass, Gateway, HTTPRoute... từ API server
- --providers.kubernetesgateway=true
# ... log, tắt kiểm tra bản mới; ports web 8000, admin 8080;
# requests 50m/64Mi, limit memory 256Mi; probe GET /ping
---
apiVersion: v1
kind: Service
metadata:
name: traefik
namespace: traefik
# ... label
spec:
# kind map 127.0.0.1:8080 của máy vào port 30080 của node control-plane (Bài 3)
type: NodePort
selector:
app.kubernetes.io/name: traefik
app.kubernetes.io/component: gateway
ports:
- name: web
port: 80
targetPort: web
nodePort: 30080
protocol: TCP
Trong đó:
controllerNamelà chuỗi Traefik nhận là của mình: Gateway dùng classtraefiksẽ do Traefik lập trình.- Traefik nghe theo entryPoint và yêu cầu port của listener trong Gateway trùng port của một entryPoint, nên Gateway sẽ khai báo port
8000. - NodePort cố định
30080, đúng portkind-config.yamlđã map ra127.0.0.1:8080từ Bài 3;30443để dành cho HTTPS. Label theo quy ước với componentgateway.
kubectl apply -f platform/traefik/
# clusterrole.rbac.authorization.k8s.io/gateway-role created
# clusterrolebinding.rbac.authorization.k8s.io/gateway-controller created
# namespace/traefik created
# serviceaccount/traefik-controller created
# gatewayclass.gateway.networking.k8s.io/traefik created
# deployment.apps/traefik created
# service/traefik created
kubectl get gatewayclass
# NAME CONTROLLER ACCEPTED AGE
# traefik traefik.io/gateway-controller True 9s
ACCEPTED là True nghĩa là đã có controller nhận class này. Pod Traefik nằm ở namespace traefik nên không bị tính vào ResourceQuota của taskflow (Bài 16).
4. Gateway và HTTPRoute cho TaskFlow.
Trong cụm nhiều team, Gateway thường nằm ở namespace hạ tầng và nhận route từ nhiều namespace. Cụm của chúng ta chỉ có TaskFlow nên mình đặt Gateway trong namespace taskflow:
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: taskflow
namespace: taskflow
labels:
app.kubernetes.io/name: taskflow
app.kubernetes.io/component: gateway
app.kubernetes.io/part-of: taskflow
spec:
# GatewayClass do Traefik xử lý (platform/traefik/traefik.yaml)
gatewayClassName: traefik
listeners:
- name: http
protocol: HTTP
# port của entryPoint web trong Traefik, không phải port người dùng gõ
port: 8000
hostname: taskflow.local
allowedRoutes:
namespaces:
# chỉ HTTPRoute cùng namespace taskflow được gắn vào
from: Same
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: taskflow-api
namespace: taskflow
labels:
app.kubernetes.io/name: taskflow-api
app.kubernetes.io/component: api
app.kubernetes.io/part-of: taskflow
spec:
parentRefs:
- name: taskflow
sectionName: http
hostnames:
- taskflow.local
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: taskflow-api
port: 80
Trong đó:
parentRefsgắn route vào listenerhttp(sectionName) của Gatewaytaskflow;hostnamesphải khớp hostname của listener.backendRefstrỏ tới Servicetaskflow-apiport 80. Traefik đọc EndpointSlice của Service và gửi thẳng tới các Pod đang Ready, nên readiness probe của Bài 15 vẫn quyết định Pod nào nhận request.
kubectl apply -f k8s/gateway.yaml -f k8s/httproute.yaml
# gateway.gateway.networking.k8s.io/taskflow created
# httproute.gateway.networking.k8s.io/taskflow-api created
kubectl get gateway
# NAME CLASS ADDRESS PROGRAMMED AGE
# taskflow traefik True 5s
Cột ADDRESS trống vì Service của Traefik là NodePort, không có IP ngoài như LoadBalancer.
Chú ý: Từ giờ kubectl apply -f k8s/ cần CRD Gateway API có trước, nếu không hai file mới báo lỗi không tìm thấy kind. Trên cụm mới, thứ tự là CRD → platform/traefik/ → k8s/namespace.yaml → k8s/.
Đọc status: Accepted, Programmed, ResolvedRefs
Mọi resource Gateway API đều có status.conditions do controller ghi, đây là chỗ đầu tiên cần xem khi route không chạy:
kubectl get gateway taskflow -o jsonpath='{range .status.conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}{range .status.listeners[*]}listener {.name}: attachedRoutes={.attachedRoutes}{"\n"}{end}'
# ResolvedRefs=True (ResolvedRefs)
# Accepted=True (Accepted)
# Programmed=True (Programmed)
# listener http: attachedRoutes=1
kubectl get httproute taskflow-api -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} ({.reason}){"\n"}{end}'
# Accepted=True (Accepted)
# ResolvedRefs=True (ResolvedRefs)
Accepted: controller chấp nhận cấu hình; với route là đã gắn được vào Gateway (đúng hostname, namespace được phép).Programmed: cấu hình đã nạp vào proxy, sẵn sàng nhận traffic.attachedRoutesđếm số route gắn vào listener.ResolvedRefs: mọi tham chiếu (Service, Secret chứa chứng chỉ) đều tìm thấy. Mình thử một route gõ nhầm Service thànhtaskflow-apii: route vẫnAcceptednhưng cóResolvedRefs=False (BackendNotFound)kèm messageservice "taskflow-apii" not found, và request khớp route đó nhận500.
Gọi TaskFlow từ máy
Thêm taskflow.local vào file hosts của máy (Windows: C:\Windows\System32\drivers\etc\hosts), rồi gọi qua port 8080:
echo "127.0.0.1 taskflow.local" | sudo tee -a /etc/hosts
curl http://taskflow.local:8080/health
# ok
curl http://taskflow.local:8080/ready
# ok
curl -i http://taskflow.local:8080/api/v1/tasks
# HTTP/1.1 401 Unauthorized
# ...
# X-Request-Id: 57QK7DWVMDPJQI3JS4VQSHTWIT
#
# {"error":"cần đăng nhập: thiếu access token"}
curl -i http://localhost:8080/health
# HTTP/1.1 404 Not Found
# ...
# 404 page not found
Không muốn sửa file hosts thì thêm --resolve taskflow.local:8080:127.0.0.1 vào lệnh curl. Response 401 có X-Request-Id của TaskFlow; còn localhost không khớp hostname nào nên Traefik tự trả 404, request không tới Pod nào. Đường đi của một request:
curl taskflow.local:8080 (máy của bạn, 127.0.0.1)
| kind: 127.0.0.1:8080 -> node taskflow-control-plane:30080
v
Service traefik (NodePort 30080 -> port web 8000)
v
Pod traefik (Gateway taskflow, listener http :8000)
| Host taskflow.local, path / -> HTTPRoute taskflow-api
v
Pod taskflow-api :8080 (endpoint Ready của Service taskflow-api)
HTTPS cần thêm listener protocol: HTTPS với chứng chỉ trong Secret; chúng ta sẽ làm ở Bài 31 với cert-manager và Let's Encrypt trên cụm thật.
5. Khớp path, header và chia traffic.
Path có ba kiểu: Exact (khớp đúng chuỗi), PathPrefix (khớp theo từng đoạn giữa các dấu /: /v1 khớp /v1/tasks nhưng không khớp /v1x) và RegularExpression (tùy implementation). Nhiều luật cùng khớp thì luật cụ thể hơn thắng: Exact trước PathPrefix, prefix dài trước prefix ngắn, rồi tới luật có nhiều header match hơn. Filter URLRewrite đổi path trước khi gửi đi, VD ReplacePrefixMatch biến /v1/tasks thành /api/v1/tasks; mình đã thử và TaskFlow log đúng path mới.
Ví dụ đầy đủ hơn là canary: cho một phần nhỏ người dùng vào bản mới trước khi chuyển hết. Rolling update (Bài 10) thay Pod dần nhưng tỷ lệ phụ thuộc số Pod; với Gateway API, tỷ lệ là weight của từng backendRef. Mình tạo bản thử taskflow-api-canary (1 Pod, Service riêng) từ chính file của project, chỉ đổi tên:
for f in deployment service; do sed -e "s/taskflow-api$/taskflow-api-canary/" -e "s/replicas: 3/replicas: 1/" k8s/$f.yaml | kubectl apply -f -; done
# deployment.apps/taskflow-api-canary created
# service/taskflow-api-canary created
Rồi thay tạm route taskflow-api bằng file thu-canary-route.yaml (cùng metadata, đổi rules): request có header X-Canary: 1 luôn vào canary, còn lại chia 90/10. Filter ResponseHeaderModifier trên từng backend gắn header X-Backend để thấy request đi đâu:
rules:
# ... luật 1: matches.headers X-Canary = "1" -> taskflow-api-canary
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: taskflow-api
port: 80
weight: 90
filters:
- type: ResponseHeaderModifier
responseHeaderModifier:
set:
- name: X-Backend
value: stable
- name: taskflow-api-canary
port: 80
weight: 10
# ... filter đặt X-Backend: canary
kubectl apply -f thu-canary-route.yaml
# httproute.gateway.networking.k8s.io/taskflow-api configured
curl -si -H "X-Canary: 1" http://taskflow.local:8080/health | grep X-Backend
# X-Backend: canary
for i in $(seq 200); do curl -s -o /dev/null -D - http://taskflow.local:8080/health | grep -i x-backend; done | sort | uniq -c
# 20 X-Backend: canary
# 180 X-Backend: stable
Đúng 10%, vì Traefik chia theo vòng có trọng số chứ không ngẫu nhiên. Muốn tăng dần thì sửa weight rồi apply lại, không đụng tới Pod; công cụ như Argo Rollouts hay Flagger tự động hóa đúng việc này. Thử xong, trả route về và xóa bản canary:
kubectl apply -f k8s/httproute.yaml
# httproute.gateway.networking.k8s.io/taskflow-api configured
kubectl delete deploy,svc taskflow-api-canary
# deployment.apps "taskflow-api-canary" deleted from taskflow namespace
# service "taskflow-api-canary" deleted from taskflow namespace
6. Ghi đúng IP client với TASKFLOW_TRUSTED_PROXIES.
Đi qua Gateway, kết nối tới TaskFlow xuất phát từ Pod Traefik, nên log request ghi "client_ip":"10.244.2.4", IP của Pod Traefik. Rate limit đăng nhập cũng đếm theo IP này (bài rate limiting của series Golang), tức mọi người dùng chung một hạn mức. Traefik có gửi X-Forwarded-For, nhưng TaskFlow chỉ tin header này khi kết nối đến từ proxy trong TASKFLOW_TRUSTED_PROXIES. IP Pod Traefik đổi mỗi lần Pod tạo lại, nên mình tin cả dải IP Pod của cụm (--cluster-cidr của kind là 10.244.0.0/16):
- k8s/configmap.yaml (thêm cuối data)
# dải IP Pod của cụm: tin X-Forwarded-For do Traefik gửi tới (Bài 17)
TASKFLOW_TRUSTED_PROXIES: 10.244.0.0/16
kubectl apply -f k8s/configmap.yaml
# configmap/taskflow-config configured
kubectl rollout restart deploy/taskflow-api && kubectl rollout status deploy/taskflow-api --timeout=120s
# deployment.apps/taskflow-api restarted
# ...
# deployment "taskflow-api" successfully rolled out
curl -s -o /dev/null http://taskflow.local:8080/api/v1/tasks
curl -s -o /dev/null -H 'X-Forwarded-For: 1.2.3.4' http://taskflow.local:8080/api/v1/tasks
kubectl logs -l app.kubernetes.io/name=taskflow-api --tail=-1 | grep '/api/v1/tasks' | jq -c '{time, client_ip, status}'
# {"time":"2026-11-24T12:36:39.116753485Z","client_ip":"192.168.164.3","status":401}
# {"time":"2026-11-24T12:36:39.131633307Z","client_ip":"192.168.164.3","status":401}
Biến môi trường từ ConfigMap chỉ đọc lúc container khởi động nên phải rollout restart (Bài 13). Giờ client_ip là IP mà Traefik nhìn thấy, còn X-Forwarded-For: 1.2.3.4 do client tự khai bị Traefik bỏ đi (mặc định Traefik không tin header này từ bên ngoài), nên không giả IP được.
192.168.164.3 là IP của node taskflow-control-plane: request vào NodePort ở node này rồi được kube-proxy chuyển sang Pod Traefik ở node khác, IP nguồn bị đổi (SNAT) thành IP node. Giữ IP gốc cần externalTrafficPolicy: Local và Pod Traefik chạy trên node nhận traffic; trên kind IP "thật" chỉ là gateway mạng Docker nên việc này để dành cho VPS ở Bài 31. Cuối cùng, kubectl apply -f k8s/ rồi kubectl diff -f k8s/ trả exit 0: cụm khớp với thư mục. Các bạn có thể xem thêm về Gateway API tại đây và provider Gateway API của Traefik tại đây.
Code đầy đủ của series sau bài này nằm ở tag bai-17 trên GitHub; các thay đổi của riêng bài này: so sánh bai-16...bai-17.
7. Lời kết.
Như vậy mình đã giới thiệu với mọi người cách đưa ứng dụng ra ngoài với Gateway API: vì sao cần một cổng vào chung, Ingress và việc ingress-nginx ngừng phát triển, ba resource GatewayClass, Gateway, HTTPRoute theo vai trò, cài CRD v1.7.0 và Traefik v3.8 trên kind, đọc status, khớp path và header, chia traffic canary, cùng TASKFLOW_TRUSTED_PROXIES để ghi đúng IP client. TaskFlow giờ gọi được bằng http://taskflow.local:8080, nhưng dữ liệu vẫn nằm trong bộ nhớ và file upload mất khi Pod khởi động lại. Bài sau chúng ta sẽ tìm hiểu volume, PersistentVolume và PersistentVolumeClaim, bắt đầu với thư mục upload của TaskFlow.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments