在Istio1.1.0以后,增强了对TCP路由的支持(Weight、Port),因为有项目使用TCP连接,故对TCP路由进行了探索;
官网示例
官方参考:TCP Traffic Shifting
官网的示例配置:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: tcp-echo-v1
spec:
replicas: 1
template:
metadata:
labels:
app: tcp-echo
version: v1
spec:
containers:
- name: tcp-echo
image: istio/tcp-echo-server:1.1
imagePullPolicy: IfNotPresent
args: [ "9000", "one" ]
ports:
- containerPort: 9000
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: tcp-echo-v2
spec:
replicas: 1
template:
metadata:
labels:
app: tcp-echo
version: v2
spec:
containers:
- name: tcp-echo
image: istio/tcp-echo-server:1.1
imagePullPolicy: IfNotPresent
args: [ "9000", "two" ]
ports:
- containerPort: 9000
---
apiVersion: v1
kind: Service
metadata:
name: tcp-echo
labels:
app: tcp-echo
spec:
ports:
- name: tcp
port: 9000
selector:
app: tcp-echo
---
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
name: tcp-echo-gateway
spec:
selector:
istio: ingressgateway
servers:
- port:
number: 31400
name: tcp
protocol: TCP
hosts:
- "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: tcp-echo
spec:
hosts:
- "*"
gateways:
- tcp-echo-gateway
tcp:
- match:
- port: 31400
route:
- destination:
host: tcp-echo
port:
number: 9000
subset: v1
weight: 80
- destination:
host: tcp-echo
port:
number: 9000
subset: v2
weight: 20
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: tcp-echo-destination
spec:
host: tcp-echo
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
以上有几点需要注意:
(1)Gateway中31340端口为istio-ingressgateway默认绑定的tcp端口,可通过istio-system.service.istio-ingressgateway进行查看;
(2)Gateway中host定义为*,表示接受所有域名,同时VirtualService中host同为*,与Gateway中host相对应;
(3)VirtualService中match.port为Gateway中监听的port 31340,并且将Gateway port 31340映射到目标应用destination port 9000端口(应用service实际端口),即将外部端口31340映射到具体tcp服务的9000端口;
使用其他(非31340)端口
官网示例中默认使用了31340端口,若想在Gateway中使用31340以外的端口(例如28674等),在Istio官网中没有提到,参考了阿里云栖社区的Istio流量管理实践之(1): 通过Istio规则来实现TCP入口流量路由的统一管理,并经过摸索,总结出若想使用31340以外的端口,则需要在istio-system.service.istio-ingressgateway中添加端口定义,例如我想在gateway中使用28674端口,则在istio-system.service.istio-ingressgateway中添加28674端口的定义,name有意义不重复即可,修改如下图:
之后便可在Gateway中使用该28674端口,否则除31340以外没有被定义的端口都是不好用的
补充:关于Istio-ingressgateway中端口定义, 可以动态添加端口定义,其中port为Gateway中监听的port,而nodePort为外部服务进入的端口,例如port=80,nodePort=31380,则通过domainName访问进入nodePort 31380端口,但是在Gateway中配置监听的port为80;