Skip to content

TCP 路由

原文:https://gateway-api.sigs.k8s.io/guides/user-guides/tcp/

INFO

实验通道(Experimental Channel)

下文涉及的 TCPRoute 资源目前仅包含在 Gateway API 的"实验"通道中。关于发布通道的更多内容,请参考 versioning 指南

Gateway API 被设计为支持多种协议,TCPRoute 就是其中一种——它用于管理 TCP 流量。

在本示例中,我们用 1 个 Gateway 资源 + 2 个 TCPRoute 资源,按以下规则分配流量:

  • Gateway 上 8080 端口的所有 TCP 流都转发到 my-foo-service 这个 Kubernetes Service 的 6000 端口。
  • Gateway 上 8090 端口的所有 TCP 流都转发到 my-bar-service 这个 Kubernetes Service 的 6000 端口。

示例中我们为 Gateway 配置了两个 TCP listener 来把流量分别路由到两个 TCPRoute 后端。注意 Gateway listeners 上的 protocol 字段被设置为 TCP

yaml
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: my-tcp-gateway
spec:
  gatewayClassName: my-tcp-gateway-class
  listeners:
  - name: foo
    protocol: TCP
    port: 8080
    allowedRoutes:
      kinds:
      - kind: TCPRoute
  - name: bar
    protocol: TCP
    port: 8090
    allowedRoutes:
      kinds:
      - kind: TCPRoute
---
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TCPRoute
metadata:
  name: tcp-app-1
spec:
  parentRefs:
  - name: my-tcp-gateway
    sectionName: foo
  rules:
  - backendRefs:
    - name: my-foo-service
      port: 6000
---
apiVersion: gateway.networking.k8s.io/v1alpha2
kind: TCPRoute
metadata:
  name: tcp-app-2
spec:
  parentRefs:
  - name: my-tcp-gateway
    sectionName: bar
  rules:
  - backendRefs:
    - name: my-bar-service
      port: 6000

在上面的示例中,我们通过 parentRefs 中的 sectionName 字段把两个后端 TCP Service 的流量区分开:

yaml
spec:
  parentRefs:
  - name: my-tcp-gateway
    sectionName: foo

直接对应到 Gateway listeners 中的 name 字段:

yaml
  listeners:
  - name: foo
    protocol: TCP
    port: 8080
  - name: bar
    protocol: TCP
    port: 8090

这样,每条 TCPRoute 都会"挂"到 Gateway 上不同的端口上 —— my-foo-service 接收来自集群外部的 8080 端口流量,my-bar-service 接收 8090 端口流量。

注意:你也可以用 parentRefs 中的 port 字段把 Route 绑定到 Gateway 的 listener 上,效果相同:

yaml
spec:
  parentRefs:
  - name: my-tcp-gateway
    port: 8080

但用 port 而非 sectionName 来做绑定,会让 Gateway 和它的 Route 之间的耦合更紧。详见 Attaching to Gateways

基于 MIT 协议发布