添加服务条目(ServiceEntry)后,Envoy代理可以将流量发送到该服务,简单的理解,就是将外部的服务加入到网格一样,从而实现针对外部服务,也可以利用一些Istio流量策略。
ServiceEntry样例
部署sleep资源
apiVersion: v1 kind: ServiceAccount metadata: name: sleep --- apiVersion: v1 kind: Service metadata: name: sleep labels: app: sleep spec: ports: - port: 80 name: http selector: app: sleep --- apiVersion: apps/v1 kind: Deployment metadata: name: sleep spec: selector: matchLabels: app: sleep template: metadata: labels: app: sleep spec: serviceAccountName: sleep containers: - name: sleep image: pstauffer/curl imagePullPolicy: IfNotPresent ports: - containerPort: 80 command: - "/bin/sleep" - "3650d"
|
配置ServiceEntry
apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: httpbin-ext spec: hosts: - httpbin.org ports: - number: 80 name: http protocol: HTTP resolution: DNS location: MESH_EXTERNAL
|
进入sleep容器
kubectl exec -it sleep-f67b89b64-8lxvb -c sleep -- sh curl http://httpbin.org/headers
|

有人会说这不就是访问外网嘛,确实是这样子,我们刚刚的YAML中配置了DNS解析,下面我们在修改下YAML看看
apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: httpbin-ext spec: hosts: - httpbin.org ports: - number: 80 name: http protocol: HTTP resolution: STATIC location: MESH_EXTERNAL endpoints: - address: 192.168.1.116
|
我们这回设置了静态域名解析,endpoints随意指向了一个内网ip,当我们内部访问 httpbin.org 的时候,Envoy就会把流量路由到我们指定的 192.168.1.116 地址去
ServiceEntry不仅仅是访问外网这么简单,他更像是通过ServiceEntry服务条目,让我们的服务访问外部服务时,就好像外部服务是网格中一样,从而让我们可以管理这部分流量。
为了验证我们这个样例,我们需要一个这样子的场景:当我们访问 http://httpbin.org/delay/5 ,本身这个地址会有5秒的延迟,我们在VirtualService中定义一个timeout字段,设定超时时长为3秒,看看是否能够正常管理ServiceEntry服务条目的流量
apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: httpbin-ext spec: hosts: - httpbin.org ports: - number: 80 name: http protocol: HTTP resolution: DNS location: MESH_EXTERNAL --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: httpbin-ext spec: hosts: - httpbin.org http: - route: - destination: host: httpbin.org port: number: 80 weight: 100 timeout: 3s
|
进入sleep容器
kubectl exec -it sleep-f67b89b64-8lxvb -c sleep -- sh curl http://httpbin.org/delay/5
|
可以看出来大概3秒的时候会返回给我们超时的信息

配置外部HTTPS服务
对于HTTPS的外部服务,除了ServiceEntry,还需要VirtualService,VirtualService中必须定义tls匹配规则和sniHosts
apiVersion: networking.istio.io/v1alpha3 kind: ServiceEntry metadata: name: httpbin-ext spec: hosts: - httpbin.org ports: - number: 443 name: https protocol: HTTPS resolution: DNS location: MESH_EXTERNAL --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: httpbin-ext spec: hosts: - httpbin.org tls: - match: - port: 443 sniHosts: - httpbin.org route: - destination: host: httpbin.org port: number: 443 weight: 100
|
进入sleep容器
kubectl exec -it sleep-f67b89b64-8lxvb -c sleep -- sh curl https://httpbin.org/headers
|