跳到主要内容

Istio 核心功能

安装

# 安装 Istio CLI
curl -L https://istio.io/downloadIstio | sh -
cd istio-*
export PATH=$PWD/bin:$PATH

# 安装到 K8s(demo profile)
istioctl install --set profile=demo -y

# 启用 Sidecar 自动注入
kubectl label namespace default istio-injection=enabled

核心 CRD 资源

VirtualService(流量路由规则)

virtual-service.yaml
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: reviews
spec:
hosts:
- reviews
http:
# 灰度:90% 流量到 v1,10% 到 v2
- route:
- destination:
host: reviews
subset: v1
weight: 90
- destination:
host: reviews
subset: v2
weight: 10
# 使用 header 路由(测试用户走 v2)
- match:
- headers:
x-user-type:
exact: beta
route:
- destination:
host: reviews
subset: v2

DestinationRule(目标规则)

destination-rule.yaml
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: reviews
spec:
host: reviews
trafficPolicy:
# 连接池
connectionPool:
tcp:
maxConnections: 100
http:
h2UpgradePolicy: DEFAULT
http1MaxPendingRequests: 100
# 熔断
outlierDetection:
consecutive5xxErrors: 5 # 连续 5 个 5xx
interval: 10s # 检测间隔
baseEjectionTime: 30s # 熔断时长
maxEjectionPercent: 50 # 最多熔断 50% 实例
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2

Gateway(入口网关)

gateway.yaml
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
name: app-gateway
spec:
selector:
istio: ingressgateway
servers:
- port:
number: 443
name: https
protocol: HTTPS
tls:
mode: SIMPLE
credentialName: app-tls-cert
hosts:
- "app.example.com"

mTLS 配置

peer-auth.yaml
# 全命名空间开启 mTLS
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: production
spec:
mtls:
mode: STRICT # STRICT=强制 mTLS, PERMISSIVE=兼容模式

可观测性

# Istio 自带的可观测性组件
kubectl apply -f samples/addons/prometheus.yaml
kubectl apply -f samples/addons/grafana.yaml
kubectl apply -f samples/addons/jaeger.yaml
kubectl apply -f samples/addons/kiali.yaml

# Kiali:服务拓扑可视化
istioctl dashboard kiali

常见面试问题

Q1: Istio 的 Sidecar 注入原理是什么?

答案

Istio 通过 Kubernetes Admission Webhook 实现自动注入:

  1. 对标记了 istio-injection=enabled 的命名空间,所有 Pod 创建请求会被拦截
  2. Admission Controller 修改 Pod Spec,注入 Envoy 容器和 init 容器
  3. init 容器通过 iptables 规则劫持所有进出流量到 Envoy
  4. Envoy 根据 Istiod 下发的 xDS 配置处理流量

整个过程对应用完全透明,无需修改业务代码。

相关链接