Phần 11 — Service Mesh: Istio, Linkerd và Cilium Service Mesh
Ý kiến
0
Chưa có ý kiến nào. Hãy là người đầu tiên chia sẻ!
Chưa có ý kiến nào. Hãy là người đầu tiên chia sẻ!
Phần cuối series K8s: Cluster API (CAPI) quản lý cluster bằng K8s API, FinOps với OpenCost + Karpenter + right-sizing, AI/ML workloads (GPU, Kubeflow, KServe, vLLM, Argo Workflows, gang scheduling), Edge K8s và WebAssembly.
Multi-tenancy K8s (soft: namespace+RBAC+Quota, HNC, Capsule, vCluster; hard: cluster riêng) và multi-cluster: management cluster, GitOps ApplicationSet, Cluster API, Karmada, Crossplane, observability liên cluster.
Production checklist K8s: observability stack (Prometheus/Loki/Tempo), backup etcd + Velero + app-level, cluster upgrade kubeadm, disaster recovery RTO/RPO, capacity planning, cost optimization, tools nên có.
Series Kubernetes Toàn Tập — 13 phần:
Phần 11 — Service Mesh ← bạn đang đọc
Đến đây bạn đã có một cluster vận hành tốt: workload đa dạng, networking, storage, security, autoscaling. Vấn đề tiếp theo bắt đầu khi microservices nhân nhanh: hàng chục, hàng trăm service nói chuyện với nhau qua HTTP/gRPC. Bạn muốn:
mTLS giữa mọi service mà không sửa code.
Retry, timeout, circuit breaker nhất quán mọi nơi.
Traffic split cho canary, blue/green, A/B test.
Quan sát request flow giữa hàng trăm service.
Policy: service A có được gọi service B không?
Có thể implement từng cái trong code (Hystrix, retry library…) nhưng không scale với nhiều ngôn ngữ và team. Service Mesh đẩy các tính năng đó xuống tầng platform, không động code app.
Service mesh đặt một proxy trước mỗi service. Toàn bộ traffic in/out của service đi qua proxy này. Proxy được điều khiển bởi control plane — cho phép admin cấu hình policy bằng YAML/CRD, không sửa code.
┌──────────────────────────────┐
│ Control Plane │ ← Istiod / Linkerd / Cilium
│ (config, certs, telemetry) │
└────────┬─────────────────────┘
│ xDS / config push
▼
┌─────────────┐ ┌─────────────┐
│ Pod A │ │ Pod B │
│ ┌─────────┐ │ │ ┌─────────┐ │
│ │ app │ │ │ │ app │ │
│ │ │◄┼─────┼─┼─ │ │
│ └────┬────┘ │ │ └────▲────┘ │
│ │ │ │ │ │
│ ┌────▼────┐ │ │ ┌────┴────┐ │
│ │ proxy │◄┼─────┼─┤ proxy │ │
│ │(Envoy) │ │ │ │(Envoy) │ │
│ └────┬────┘ │ │ └────▲────┘ │
└──────┼──────┘ └──────┼──────┘
└────── mTLS ───────┘
| Mô hình | Triển khai | Đại diện |
|---|---|---|
| Sidecar | Mỗi pod thêm 1 container proxy | Istio (classic), Linkerd |
| Sidecarless / per-node | 1 proxy / node, hoặc dùng eBPF | Cilium, Istio Ambient |
Sidecar đơn giản, cô lập tốt, nhưng tốn CPU/RAM (mỗi pod 50–200MB cho Envoy). Sidecarless tiết kiệm tài nguyên hơn nhưng phức tạp hơn về isolation và debugging.
mTLS automatic — proxy gắn cert, mã hoá traffic L4/L7.
Traffic management: routing theo header/path, weight, mirror, fault inject.
Resilience: retry, timeout, circuit breaker, outlier detection.
Observability: metrics RED (Rate/Error/Duration) per request, distributed tracing.
AuthZ: rule allow/deny ở tầng L7 (HTTP method, path, header, JWT claim).
Istio (Google + IBM + Lyft, sau là CNCF graduated 2023) dùng Envoy làm proxy. Có 2 mode:
# Cài Istio
istioctl install --set profile=demo -y
# Bật auto-inject sidecar cho namespace
kubectl label namespace prod istio-injection=enabled
Mọi Pod tạo mới trong prod sẽ có thêm container istio-proxy. Pod cũ phải restart để inject.
Thay sidecar bằng:
ztunnel (DaemonSet trên mọi node) — xử lý mTLS L4.
waypoint proxy (Deployment per namespace/SA) — xử lý L7 khi cần.
istioctl install --set profile=ambient
kubectl label namespace prod istio.io/dataplane-mode=ambient
Pod không có sidecar, traffic vẫn được mã hoá mTLS, có thể opt-in L7 bằng waypoint khi cần routing/retry/JWT.
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata:
name: api
spec:
hosts: ["api"]
http:
- match:
- headers:
x-canary:
exact: "true"
route:
- destination:
host: api
subset: v2
- route:
- destination:
host: api
subset: v1
weight: 90
- destination:
host: api
subset: v2
weight: 10
retries:
attempts: 3
perTryTimeout: 2s
timeout: 10s
---
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata:
name: api
spec:
host: api
trafficPolicy:
connectionPool:
tcp: { maxConnections: 100 }
http: { http2MaxRequests: 1000 }
outlierDetection:
consecutive5xxErrors: 5
interval: 30s
baseEjectionTime: 30s
subsets:
- name: v1
labels: { version: v1 }
- name: v2
labels: { version: v2 }
Header x-canary: true đi vào v2; còn lại 90/10 v1/v2. Có retry, timeout, outlier detection.
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
name: default
namespace: prod
spec:
mtls:
mode: STRICT # PERMISSIVE / STRICT / DISABLE
STRICT: chỉ chấp nhận mTLS, từ chối plaintext. Migration thường bắt đầu PERMISSIVE (chấp nhận cả 2), rồi siết lên STRICT.
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
name: api-allow-from-frontend
namespace: prod
spec:
selector:
matchLabels: { app: api }
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/prod/sa/frontend"]
to:
- operation:
methods: ["GET", "POST"]
paths: ["/api/*"]
when:
- key: request.auth.claims[role]
values: ["user", "admin"]
Quy tắc kết hợp: identity (SA), HTTP method/path, và JWT claim. Không có rule = mặc định deny.
Linkerd (Buoyant, CNCF graduated 2021) là đối thủ lớn của Istio. Triết lý: nhẹ, đơn giản, đủ dùng. Không dùng Envoy — dùng proxy Rust riêng (linkerd2-proxy) nhỏ hơn 10×.
linkerd install --crds | kubectl apply -f -
linkerd install | kubectl apply -f -
linkerd check
linkerd viz install | kubectl apply -f - # dashboard
# Auto-inject
kubectl annotate namespace prod linkerd.io/inject=enabled
apiVersion: split.smi-spec.io/v1alpha2
kind: TrafficSplit
metadata:
name: api
spec:
service: api
backends:
- service: api-v1
weight: 90
- service: api-v2
weight: 10
Mesh đầu tiên của team — ít CRD hơn, học nhanh.
Resource budget hẹp — proxy Linkerd nhẹ 5–10 MB RAM/pod.
Không cần nhiều feature L7 phức tạp.
Nếu cần policy phức tạp, JWT, WASM filter, multi-cluster mature → Istio mạnh hơn.
Cilium đã là CNI eBPF mạnh. Từ Cilium 1.12+ thêm service mesh:
L4 mTLS làm trong eBPF/kernel — không proxy.
L7 routing dùng Envoy chạy per node (không phải per pod).
Tích hợp Gateway API thay cho VirtualService riêng.
Không sidecar = không tốn RAM mỗi pod.
Latency thấp (kernel-level forwarding).
1 stack: CNI + Service Mesh + Gateway + Network Policy.
Yêu cầu kernel ≥ 5.10 cho mọi feature.
Hệ sinh thái CRD chưa lớn bằng Istio.
Debug khó hơn vì traffic không đi qua proxy thấy được.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: api-canary
spec:
parentRefs:
- name: prod-gateway
rules:
- matches:
- headers:
- name: x-canary
value: "true"
backendRefs:
- name: api-v2
port: 80
- backendRefs:
- name: api-v1
port: 80
weight: 90
- name: api-v2
port: 80
weight: 10
| Tiêu chí | Istio | Linkerd | Cilium SM |
|---|---|---|---|
| Proxy | Envoy (sidecar/ambient) | linkerd2-proxy (Rust) | eBPF + Envoy/node |
| RAM overhead/pod | 50–200 MB | 5–10 MB | ~0 (per-node) |
| mTLS | Có | Có | Có |
| L7 policy | Mạnh | Cơ bản | Mạnh qua Envoy |
| Multi-cluster | Trưởng thành | Có | Cluster Mesh, eBPF native |
| Học curve | Cao | Thấp | Trung bình |
| Khi nên dùng | Mesh enterprise đa feature | Mesh đơn giản, ít overhead | Đã dùng Cilium CNI |
Split traffic 95/5 hai version, theo dõi error/latency v2, tăng dần weight nếu OK, rollback nếu lỗi. Argo Rollouts / Flagger tự động hoá pattern này dựa trên Prometheus metric.
Send 100% traffic đến v1 (response trả về user), đồng thời copy đến v2 (response bỏ). Dùng để test v2 với traffic thật mà không ảnh hưởng user.
Inject delay hoặc HTTP 500 với % traffic để kiểm tra resilience:
http:
- fault:
delay:
percentage:
value: 10
fixedDelay: 5s
abort:
percentage:
value: 1
httpStatus: 500
route: [...]
Khi upstream lỗi liên tiếp, mesh tạm ngừng gửi request đến nó (eject), tránh lan toả lỗi (cascading failure).
Một trong lợi ích lớn nhất: mọi request đều có metrics + trace mà app không phải instrument.
Metrics: istio_requests_total, istio_request_duration_milliseconds, istio_request_bytes. Cardinality cao — cân nhắc filter label.
Distributed tracing: mesh tự gắn trace header (B3 / W3C TraceContext). App cần forward header sang downstream để chain trace.
Access log: mỗi proxy log request, ship vào Loki/Elastic.
Kiali (Istio) — visualize service graph, traffic flow real-time.
Khi có ≥ 2 cluster, mesh giúp service ở cluster A gọi service ở cluster B như local.
Primary-remote — 1 control plane, nhiều cluster data plane.
Multi-primary — mỗi cluster có control plane riêng, đồng bộ qua trust.
Cilium dùng kvstore (etcd-mesh hoặc cluster identity) cho phép pod cluster A gọi service cluster B với policy chia sẻ.
Multi-cluster mesh phức tạp — chỉ làm khi đã thuần thục single-cluster mesh.
Mesh không miễn phí — overhead CPU/RAM, thêm CRD, thêm điểm fail, debug khó.
App ít service (< 10) → NetworkPolicy + Ingress đủ.
Team chưa quen container/K8s → mesh sẽ là cú sốc.
Mục tiêu chính là TLS in-cluster → có thể dùng cert-manager + app-level TLS, không cần mesh.
Khi performance latency < 5ms quan trọng → đo carefully, mesh thêm 1–3ms per hop.
# Trước/sau khi inject mesh:
# - p50/p99 latency của request giữa 2 service.
# - CPU/RAM container app vs proxy.
# - Throughput RPS.
# Tools: fortio, vegeta, hey.
fortio load -qps 200 -t 60s http://api/
Một sidecar Envoy idle thường chiếm 20–50m CPU, 100–200Mi RAM. × 500 pod = 10–25 CPU, 50–100Gi RAM cho riêng mesh.
Bắt đầu với PERMISSIVE mTLS, dần dần STRICT theo namespace.
Không bật mesh toàn cluster ngay — opt-in từng namespace, có A/B đo overhead.
Tách data plane (Envoy/proxy) và control plane (Istiod) về compute pool khác nhau; control plane HA ≥ 2 replica.
Mesh upgrade phức tạp — staging trước, tận dụng revision-based upgrade (Istio): chạy 2 control plane song song.
Gateway API > VirtualService riêng — chuẩn hoá tương lai, support đa mesh.
Hạn chế gọi external service qua mesh ngay; dùng ServiceEntry / egress gateway rõ ràng.
Đặt PodDisruptionBudget cho mesh control plane và gateway.
Monitor cardinality Prometheus — mesh tự sinh hàng triệu label tag nếu không filter.
# Istio
istioctl proxy-config cluster <pod> -n prod
istioctl proxy-config listener <pod> -n prod
istioctl proxy-config route <pod> -n prod
istioctl analyze
# Linkerd
linkerd check
linkerd viz tap deploy/api
linkerd viz stat deploy
# Cilium
cilium status
cilium connectivity test
hubble observe --pod prod/api
Service mesh đẩy mTLS, retry, traffic split, observability xuống tầng platform.
Istio: powerful, feature đầy đủ, có ambient mode mới.
Linkerd: gọn, nhẹ, học nhanh.
Cilium Service Mesh: sidecarless qua eBPF, hợp khi đã dùng Cilium CNI.
Mesh không miễn phí — đo overhead trước khi bật toàn cluster.
Khi service ít, NetworkPolicy + cert-manager + Ingress đủ — không cần mesh.
Phần 12: multi-tenancy và multi-cluster — khi 1 cluster, 1 namespace per team không còn đủ.