Istio 常见问题 - 如何为公开多个端口的服务配置 VirtualService?

背景

有一个暴露多个端口的容器,Kubernetes Service 的配置如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
apiVersion: v1
kind: Service
metadata:
  name: myapp
spec:
  ports:
    - name: http
      protocol: TCP
      port: 8080
      targetPort: 8080
    - name: http-addition
      protocol: TCP
      port: 8001
      targetPort: 8001
---

现在使用 Istio 来管理路由并通过 Istio Ingress Gateway 公开此服务。想要配置 的 80 端口路由到 Service 的 8080 端口,8001 端口路由到 Service 的 8001 端口。一个 VirtualService 可以做到吗?

解决方法

只用一个 VirtualService 是可以做到的,步骤如下:

  1. Istio Ingress Gateway 中增加需要暴露的端口
  2. 建立 Gateway
  3. 建立 VirtualService

Istio Ingress Gateway 中增加需要暴露的端口

暴露端口的目的是让流量能通过该端口进入到 Service Mesh(Istio)。以 myapp 为例,除了默认暴露的 80 端口,还需要暴露 8001 端口。关于如何自定义暴露的端口,可以参考 Istio 自定义 Ingress(入口)网关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
spec:
  profile: default
  components:
    # ingressGateways 是个数组
    ingressGateways:
      # Istio 默认创建的入口网关,可保留
      - name: istio-ingressgateway
        enabled: true
        k8s:
          service:
            # 自定义暴露的端口
            ports:
            - port: 80
              targetPort: 80
              name: http2
            - port: 443
              name: https
            ......
            # 以上端口是 istio 默认的端口,8001 端口是增加的自定义端口
            - port: 8001
              targetPort: 8001
              name: http-addition

建立 Gateway

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# See more at https://istio.io/docs/reference/config/networking/gateway/
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: myapp-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 80
        name: http
        protocol: HTTP
      hosts:
        - "example.makeoptim.com"
    - port:
        number: 8001
        name: http-addition
        protocol: HTTP
      hosts:
        - "example.makeoptim.com"

建立 VirtualService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: myapp-virtual-service
spec:
  hosts:
    - example.makeoptim.com
  gateways:
    - myapp-gateway
  http:
    - match:
        - port: 80
      route:
        - destination:
            host: myapp
            port:
              number: 8080
    - match:
        - port: 8001
      route:
        - destination:
            host: myapp
            port:
              number: 8001

参考

延伸阅读


CatchZeng
Written by CatchZeng Follow
AI (Machine Learning) and DevOps enthusiast.