Istio 例子(基于用户身份路由)
Istio 对用户身份没有任何特殊的内置机制。通过对 HTTP 请求中增加了一个自定义的 user 请求头达到效果。
创建应用
vi myapp-demo.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-svc
spec:
ports:
- port: 80
name: http
selector:
app: myapp-pod
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-v1
labels:
app: myapp-pod
version: v1
spec:
replicas: 1
selector:
matchLabels:
app: myapp-pod
version: v1
template:
metadata:
labels:
app: myapp-pod
version: v1
spec:
containers:
- name: myapp-pod
image: ikubernetes/myapp:v1
ports:
- containerPort: 80
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-v2
labels:
app: myapp-pod
version: v2
spec:
replicas: 1
selector:
matchLabels:
app: myapp-pod
version: v2
template:
metadata:
labels:
app: myapp-pod
version: v2
spec:
containers:
- name: myapp-pod
image: ikubernetes/myapp:v2
ports:
- containerPort: 80
kubectl apply -f myapp-demo.yaml
# 创建规则
vi gateway.yaml
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: myapp-gateway
spec:
selector:
istio: ingressgateway # use istio default controller
servers:
- port:
number: 80
name: http
protocol: HTTP
hosts:
- "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: myapp-vs
spec:
hosts:
- "*"
gateways:
- myapp-gateway
http:
- match:
- headers:
user: # 自定义一个 user 请求头
exact: klvchen # 匹配 klvchen 这个值
route:
- destination:
host: myapp-svc.default.svc.cluster.local
subset: v1
- route: # 默认走这条规则
- destination:
host: myapp-svc.default.svc.cluster.local
subset: v2
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: myapp-dr
namespace: default
spec:
host: myapp-svc.default.svc.cluster.local
subsets:
- labels:
version: v1
name: v1
- labels:
version: v2
name: v2
kubectl apply -f gateway.yaml
测试, 172.18.34.35:32151 为 ingress 的 nodeport 的IP和端口
curl http://172.18.34.35:32151/
curl -H 'user:klvchen' http://172.18.34.35:32151/ # 指定自定义请求头
参考:https://istio.io/latest/docs/tasks/traffic-management/request-routing/