Part 12 · Kubernetes · Networking · 12.1.06a

Ingress là API; controller mới xử lý traffic

Ingress mô tả desired L7 routing, nhưng bản thân object không tạo reverse proxy. Ingress Controller watch Kubernetes API, reconcile rule thành cấu hình data plane và cập nhật status. Với thiết kế mới, Kubernetes khuyến nghị Gateway API; Ingress vẫn GA nhưng API đã frozen.

Mental model: tách control plane (Ingress/Gateway objects + controller reconciliation) khỏi data plane (proxy/LB thực sự nhận connection). Khi debug, luôn xác định request đang hỏng ở lớp nào.

Request path đầy đủ

Client / DNS
  → cloud Load Balancer hoặc NodePort
  → Ingress Controller data plane (Nginx, Traefik, HAProxy, Envoy...)
  → host/path rule match
  → Service ClusterIP / EndpointSlice
  → ready Pod IP : targetPort
  → application container

Controller có thể chạy dưới dạng Deployment hoặc DaemonSet và được expose bằng Service type LoadBalancer, NodePort hoặc integration riêng của platform. Một thay đổi Ingress/Gateway trước hết đi qua reconciliation; chỉ sau khi data plane nhận config mới thì traffic mới thực sự thay đổi.

Failure window khi rollout config: API object có thể đã được accepted nhưng proxy config chưa áp dụng xong, certificate chưa load, endpoint chưa ready hoặc LB/DNS chưa hội tụ. Vì vậy status condition, controller log, config reload error và request probe phải được quan sát cùng nhau.

Ingress resource tối thiểu

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: banking-web
spec:
  ingressClassName: nginx
  tls:
    - hosts: [bank.example.com]
      secretName: bank-tls
  rules:
    - host: bank.example.com
      http:
        paths:
          - path: /api
            pathType: Prefix
            backend:
              service:
                name: banking-api
                port:
                  number: 8080
          - path: /
            pathType: Prefix
            backend:
              service:
                name: banking-web
                port:
                  number: 80

backend.service.portService port, không nhất thiết là container port. Service tiếp tục map port → targetPort. Ingress chuẩn route tới Service trong cùng namespace; nhu cầu cross-namespace nên dùng cơ chế có permission rõ, ví dụ Gateway API với ReferenceGrant, thay vì giả định mọi controller có cùng extension.

IngressClass và controller ownership

ingressClassName xác định controller/class chịu trách nhiệm. Một cluster có thể có public và internal controllers; ownership phải rõ để tránh hai controller cùng reconcile một route hoặc không controller nào nhận route.

apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
  name: nginx
spec:
  controller: k8s.io/ingress-nginx

spec.controller, annotations và feature support phụ thuộc implementation. Annotation của NGINX Ingress không mặc nhiên dùng được cho AWS ALB, Traefik hoặc controller khác. Khi thay controller, hãy coi annotation/config-specific behavior là migration surface cần test.

pathType: Exact, Prefix, ImplementationSpecific

TypeÝ nghĩaCảnh báo
ExactMatch URL path chính xác, case-sensitive./api không tự match /api/orders.
PrefixMatch theo path elements; /api match /api/orders.Phải hiểu boundary segment và test trailing slash.
ImplementationSpecificController quyết định semantics.Regex/rewrite có portability thấp và thường cần extension/annotation.

Rule precedence, regex, merge và conflict giữa nhiều Ingress objects có thể controller-specific. Với host/path quan trọng, thêm probe cho positive case, negative case, trailing slash và path gần giống để phát hiện route shadowing.

TLS termination và certificate lifecycle

Operational signals: certificate expiry horizon, renewal failures, handshake errors, default-certificate hits, TLS version/cipher policy, reload success và tỷ lệ 4xx/5xx sau rotation.

Headers và client identity

Controller thường thêm Forwarded hoặc X-Forwarded-For/Proto/Host. Application chỉ nên tin các header này khi request đến từ trusted proxy chain; edge phải strip/overwrite header do client tự gửi nếu dùng chúng cho authorization, redirect, audit hoặc rate-limit.

externalTrafficPolicy, proxy protocol và cloud LB behavior có thể thay đổi client IP nhìn thấy ở proxy/app. Sai trust configuration có thể gây redirect loop, insecure cookie, forged audit IP hoặc bypass policy dựa trên source address.

Timeout, buffering, body size và retry

Phần lớn timeout, buffering, body/header limit và retry là controller-specific chứ không phải portable Ingress API. Deadline của proxy phải nằm trong end-to-end latency budget và tương thích với upstream/downstream timeouts.

Không retry POST payment mù: proxy không biết database đã commit hay payment provider đã charge. Retry write chỉ an toàn khi operation replay-safe hoặc application có idempotency key, deduplication và unknown-outcome reconciliation.

Rewrite và SPA routing

Rewrite thay URL trước khi gửi backend; strip prefix sai thường tạo 404 hoặc route nhầm. Với SPA, fallback /index.html nên thuộc static/frontend routing boundary; không rewrite mọi API/asset 404 thành HTML 200 vì sẽ che lỗi thật. Giữ original URI trong access log/tracing để điều tra được request trước và sau rewrite.

Ingress khác Service LoadBalancer thế nào?

Service LoadBalancerIngress
LayerThường L4 TCP/UDP, tùy providerL7 HTTP/HTTPS routing
ExposureMỗi Service có thể cần LB riêngMột controller/LB có thể route nhiều Services
RoutingPort tới một ServiceHost/path tới nhiều Services
ImplementationCloud/controller integrationCần Ingress Controller

Hai mô hình thường phối hợp: Ingress Controller chính nó có thể được expose bằng một Service LoadBalancer. Vì vậy câu hỏi không phải luôn là “chọn một trong hai”, mà là layer nào chịu trách nhiệm L4 exposure và layer nào chịu trách nhiệm L7 routing.

Gateway API: successor có role model rõ hơn

Kubernetes hiện khuyến nghị Gateway thay vì mở rộng thêm Ingress. Gateway API tách ownership infrastructure và application routing rõ hơn:

GatewayClass   → implementation/controller của platform
Gateway        → listener, address, TLS; platform team quản
HTTPRoute      → host/path/header/backend; app team quản
ReferenceGrant → cho phép cross-namespace reference có chủ đích

HTTPRouteReferenceGrant thuộc Standard Channel/GA. Gateway API có typed routes, richer matching, explicit attachment/status và permission model tốt hơn cho cross-namespace references. Tuy vậy, feature support thực tế vẫn phụ thuộc controller/conformance profile, nên phải kiểm tra implementation trước khi migration.

apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: banking-api
spec:
  parentRefs:
    - name: public-gateway
  hostnames: [bank.example.com]
  rules:
    - matches:
        - path: { type: PathPrefix, value: /api }
      backendRefs:
        - name: banking-api
          port: 8080
          weight: 90
        - name: banking-api-canary
          port: 8080
          weight: 10
Migration guardrail: chạy canary/shadow host hoặc weighted route nếu controller hỗ trợ; so status conditions, access logs, latency/error rate và certificate behavior; giữ Ingress cũ làm rollback path cho tới khi traffic evidence ổn định.

Debug từ ngoài vào trong

  1. DNS có resolve đúng LB address? TLS handshake, SNI, certificate và HTTP status là gì?
  2. Ingress/Gateway đã accepted/programmed chưa? Kiểm tra class, status/conditions, events và controller logs.
  3. Host/path/pathType có match request thực tế?
  4. Backend Service tồn tại và Service port name/number đúng?
  5. EndpointSlice có ready Pod IP và targetPort đúng?
  6. Pod có listen 0.0.0.0, readiness true và NetworkPolicy cho phép?
  7. Proxy upstream log báo connect timeout, reset, 502, 503 hay 504?
  8. Application trace/log có nhận request và forwarded headers đúng?
SymptomNghi ngờ đầu tiênSignal cần xem
404 từ controllerHost/path/class/rule hoặc default backendMatched route, access log, config dump/status
502Endpoint/listener/targetPort/protocol/resetUpstream connect/reset, EndpointSlice
503No ready endpoints hoặc upstream unavailableReady endpoints, readiness, controller health
504Backend chậm hoặc timeout budget saiUpstream latency, saturation, deadline
Redirect loopForwarded proto/trust/TLS terminationX-Forwarded-Proto, app redirect log
Certificate saiDNS/SNI/Secret/host/default certificatePresented cert, secret revision, reload event

Capacity, security và recovery checklist

Câu hỏi phỏng vấn

Tạo Ingress nhưng không truy cập được, vì sao?
Ingress chỉ mô tả desired route. Cần controller nhận đúng IngressClass, controller được expose, status/address sẵn sàng, DNS trỏ đúng, rules match, Service/EndpointSlice/Pods healthy và policy cho phép.
Ingress Controller khác Ingress resource?
Ingress resource là config API; controller watch/reconcile resource và vận hành hoặc cấu hình proxy data plane thực sự nhận traffic.
Gateway API tốt hơn ở đâu?
Gateway API có role separation, attachment/status rõ hơn, typed routes, richer matching/traffic policy và cross-namespace reference có permission rõ. Nhưng migration vẫn phụ thuộc controller support, conformance và cost chuyển đổi.
Tài liệu: Kubernetes Ingress · Ingress Controllers · Gateway API HTTPRoute · Gateway API ReferenceGrant.