无外部LB时,如何通过Istio在同一主机暴露UI与API微服务?
问题描述
- K8s环境为开发机,无外部负载均衡器,已启用Istio,默认命名空间部署UI、API两个微服务
- UI服务:端口80映射容器端口80
- API服务:端口8000映射容器端口80
- 需求:对外暴露两个服务,支持用户访问UI或通过Postman调用
/api路径的JSON-RPC API - 原Docker部署时访问方式:
- UI:
host.example.com - API:
host.example.com:8000/api
- UI:
- 当前状态:已配置Gateway和VirtualService,UI可通过
http://host.example.com:31165访问,但API无法外部访问
解决方案
方案一:路径路由(推荐,无需额外端口)
修改步骤
- 合并Gateway:无需单独创建API的Gateway,复用统一的
app-gateway即可
统一Gateway配置示例:apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: app-gateway spec: selector: istio: ingressgateway servers: - port: number: 80 name: http protocol: HTTP hosts: - host.example.com - 调整UI的VirtualService:添加根路径匹配(Istio会自动优先匹配更长的路径前缀,不会和API路由冲突)
apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: ui-vs spec: hosts: - host.example.com gateways: - app-gateway http: - match: - uri: prefix: / route: - destination: host: ui port: number: 80 - 修改API的VirtualService:添加
/api路径匹配,绑定到统一GatewayapiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: api-vs spec: hosts: - host.example.com gateways: - app-gateway http: - match: - uri: prefix: /api route: - destination: host: api port: number: 8000
访问方式
- UI:
http://host.example.com:31165 - API:
http://host.example.com:31165/api
方案二:独立端口路由(贴近原Docker访问方式)
如果需要保留8000端口的访问形式,需额外配置IngressGateway的NodePort:
修改步骤
- 修改Istio IngressGateway Service:添加8000端口的NodePort映射
执行命令编辑服务:
在kubectl edit svc istio-ingressgateway -n istio-systemports字段下新增配置:- name: http-api port: 8000 targetPort: 8000 nodePort: 31166 # 可指定端口,或留空让K8s自动分配 - 更新API的Gateway:监听8000端口
apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: api-gateway spec: selector: istio: ingressgateway servers: - port: number: 8000 name: http-api protocol: HTTP hosts: - host.example.com - 保留原API VirtualService(确保
gateways字段指向api-gateway)
访问方式
- UI:
http://host.example.com:31165 - API:
http://host.example.com:31166/api(替换为实际分配的NodePort)
内容的提问来源于stack exchange,提问作者user1452759
相关产品推荐
相关产品推荐

