Part 12 · Kubernetes · 12.1.06

Pod network, Services, DNS và Gateway

Pod IP là identity mạng có vòng đời theo Pod; Service tạo một điểm truy cập ổn định tới tập backend thay đổi theo thời gian. Hiểu đúng lớp Pod network, Service/EndpointSlice, DNS, north-south routing và NetworkPolicy giúp debug theo từng hop thay vì đoán.

Mental model: Pod network trả lời “packet đi tới Pod bằng cách nào”; Service trả lời “client tìm và cân bằng tới backend nào”; DNS trả lời “name resolve thành gì”; Ingress/Gateway xử lý traffic vào cluster; NetworkPolicy quyết định flow L3/L4 nào được phép. Các lớp này liên quan nhưng không thay thế nhau.

1. Network model

CNI plugin (hoặc dataplane tương đương của distribution) tạo network interface, cấp IP, route và có thể enforce NetworkPolicy cho Pod. Các container trong cùng một Pod chia sẻ network namespace nên giao tiếp qua localhost; giữa các Pod, ứng dụng nên coi Pod IP là địa chỉ có thể thay đổi khi Pod bị recreate.

Service có selector thường được control plane ánh xạ sang EndpointSlice chứa các backend phù hợp. Service proxy/dataplane quan sát Service và EndpointSlice rồi lập trình đường đi tới backend. Kubernetes có kube-proxy làm implementation mặc định, nhưng một số network implementation dùng dataplane riêng.

Client Pod | | DNS: api.default.svc.cluster.local v ClusterIP Service | | service dataplane / proxy v EndpointSlice +-------------------+ | | Pod A :8080 Pod B :8080

Đừng nhầm Service với process proxy

Service là API abstraction và virtual endpoint. Việc packet được NAT, load-balance hoặc chuyển tiếp cụ thể phụ thuộc dataplane/implementation. Vì vậy khi debug cần kiểm tra cả object Kubernetes lẫn implementation đang thực thi nó.

Failure window và signals

2. Service types và EndpointSlice

TypeDùng khiĐiểm cần nhớ
ClusterIPTraffic nội bộ clusterMặc định. Cấp virtual IP nội bộ và route tới backend.
NodePortCần mở cùng một port trên các nodeXây trên ClusterIP; client truy cập NodeIP:NodePort. Cần firewall/security review.
LoadBalancerExpose ra ngoài qua LB integrationKubernetes cần cloud/provider hoặc implementation cung cấp load balancer; không tự tạo external LB thuần túy.
ExternalNameAlias một DNS name bên ngoàiTrả DNS alias/CNAME; không proxy traffic và không tạo backend Pod.
Headless (clusterIP: None)Client cần thấy trực tiếp endpoint, thường stateful/discoveryKhông có virtual ClusterIP; DNS có thể trả tập IP endpoint để client tự lựa chọn.

EndpointSlice là representation chuẩn của tập endpoint phía sau Service. Khi một selector match nhiều Pod, controller cập nhật EndpointSlice thay vì buộc client quan tâm Pod lifecycle trực tiếp.

apiVersion: v1
kind: Service
metadata:
  name: api
spec:
  selector:
    app: api
  ports:
    - name: http
      port: 80
      targetPort: 8080
  type: ClusterIP

Debug Service theo chuỗi

  1. kubectl get svc api -o wide — type, ClusterIP, ports có đúng không?
  2. kubectl get endpointslice -l kubernetes.io/service-name=api — có endpoint không?
  3. kubectl get pods -l app=api -o wide — selector có match đúng Pod và Pod có Ready không?
  4. Test trực tiếp Pod IP/port từ debug Pod để tách lỗi application khỏi lỗi Service dataplane.
  5. Test qua Service DNS/ClusterIP; nếu direct Pod chạy nhưng Service fail, tập trung vào Service/EndpointSlice/dataplane.

3. DNS và service discovery

Cluster DNS (thường là CoreDNS trong nhiều cluster) cung cấp DNS records cho Service/Pod theo cấu hình cluster. Pod mặc định có search domain liên quan namespace, vì vậy tên ngắn như api thường chỉ resolve Service cùng namespace; cross-namespace nên dùng api.backend hoặc FQDN đầy đủ như api.backend.svc.cluster.local nếu cluster domain là cluster.local.

Truy vấnÝ nghĩa điển hình
apiTìm Service api trong namespace hiện tại qua search domain.
api.backendTìm Service api trong namespace backend.
api.backend.svc.cluster.localFQDN, tránh ambiguity do search path.
Headless Service nameCó thể resolve thành tập IP endpoint thay vì một ClusterIP.

DNS failure modes

# Trong debug pod
cat /etc/resolv.conf
nslookup api.backend.svc.cluster.local
# hoặc dùng dig nếu image có sẵn
dig api.backend.svc.cluster.local
Production signal: monitor DNS latency/error rate, CoreDNS CPU/memory, cache hit/miss nếu có, upstream failures và query volume. DNS saturation có thể nhìn giống lỗi application ngẫu nhiên trên toàn cluster.

4. Ingress và Gateway API

Ingress và Gateway chỉ là API/configuration object; muốn traffic thực sự đi qua cần controller/implementation tương ứng. Ingress tập trung vào HTTP/HTTPS routing và API của Ingress hiện đã frozen. Kubernetes khuyến nghị Gateway API cho hướng phát triển mới.

Gateway API tách trách nhiệm rõ hơn: GatewayClass mô tả loại implementation, Gateway yêu cầu một điểm nhận traffic/listener, còn Route như HTTPRoute mô tả routing tới backend Service. Mô hình này phù hợp cluster dùng chung vì infrastructure provider, cluster operator và application developer có thể có quyền khác nhau.

Internet / client | v Load balancer / Gateway implementation | v Gateway listener (:443, TLS) | v HTTPRoute (host/path/header rules) | v Service | v Ready Pods

Những behavior phải đọc theo implementation

Security và rollout

Không để application team mặc định có toàn quyền sửa shared GatewayClass/Gateway nếu cluster multi-tenant. Dùng RBAC theo ownership, giới hạn listener/namespace attachment theo policy của implementation, rotate TLS secret/certificate có kiểm soát và quan sát status conditions trước khi chuyển traffic.

Khi migrate Ingress → Gateway API, chạy canary route/hostname nếu có thể, xác minh TLS, headers, redirects, timeout, websocket/gRPC behavior và log/metrics. Rollback nên giữ manifest/implementation cũ đủ lâu để quay lại mà không tạo hai đường ingress cạnh tranh cho cùng hostname.

5. NetworkPolicy

NetworkPolicy là Kubernetes API để kiểm soát traffic ở lớp IP/port. Policy chỉ có hiệu lực nếu network plugin/dataplane của cluster hỗ trợ enforcement. Việc object tạo thành công không chứng minh traffic đã bị chặn.

Policy là additive: nhiều policy chọn cùng Pod thì tập allow là union của các rule liên quan, không có thứ tự “policy sau override policy trước”. Ingress và egress isolation được xét độc lập; để một kết nối Pod-to-Pod thành công, phía source phải được phép egress và phía destination phải được phép ingress khi các phía đó đang bị isolate.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: backend
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress

Sau default-deny, thêm allow rule tối thiểu cho dependencies thật sự cần thiết. Đặc biệt, default-deny egress cũng có thể chặn DNS; phải allow DNS tới resolver của cluster theo cách phù hợp với distribution/CNI của bạn.

Selector semantics dễ sai

Debug và rollback

  1. Xác nhận CNI có support NetworkPolicy và policy engine đang healthy.
  2. Xem label thực tế của source Pod, destination Pod và Namespace.
  3. Kiểm tra cả ingress lẫn egress policy đang chọn hai phía.
  4. Test DNS riêng, sau đó test IP/port dependency bằng debug Pod có cùng labels/service account/context cần thiết.
  5. Nếu rollout policy làm gián đoạn production, rollback bằng cách gỡ policy mới hoặc áp dụng temporary explicit allow có scope hẹp; sau đó thu evidence trước khi chỉnh lại rule.
Không dùng “allow all” lâu dài để chữa cháy. Nếu cần temporary bypass, đặt owner/time window rõ ràng và theo dõi để tránh biến exception thành baseline security mới.

6. Runbook: phân lớp sự cố networking

Triệu chứngKhoanh vùng đầu tiênEvidence nên lấy
Name không resolveDNS policy/search path/CoreDNS/upstream/etc/resolv.conf, DNS query, CoreDNS logs/metrics
DNS resolve nhưng connect failService endpoints, targetPort, NetworkPolicy, app listenerService YAML, EndpointSlice, Pod readiness, direct Pod test
Chỉ external traffic failLB/Gateway/Ingress/controller/firewall/TLSGateway/Ingress status, LB health, controller logs, certificate state
Một số Pod fail ngẫu nhiênBad endpoint, readiness gap, zone/node path, stale connectionPer-endpoint error, Pod/node mapping, connection age
Sau NetworkPolicy rollout bị timeoutSelector/egress DNS/dependency portMatched policy, labels, CNI policy verdict/log nếu có

7. Production checklist

Tài liệu chính thức: Services, Load Balancing, and Networking · Service · DNS for Services and Pods · Ingress · Gateway API in Kubernetes · Gateway API Overview · Network Policies