# 按端口代理 UDP 流量

使用 Gateway API UDPRoute 或 APISIX CRD stream route，按网关入站端口将 UDP 流量路由到 echo Service。

## 前置条件[​](#前置条件 "前置条件的直接链接")

1. 完成[设置 Ingress Controller 和网关](https://docs.apiseven.com/ingress-controller/set-up-ingress-controller-and-gateway.md)。

## 启动示例上游服务[​](#启动示例上游服务 "启动示例上游服务的直接链接")

创建 Kubernetes manifest 文件，定义监听 `9000` 端口的 UDP echo server：

udp-echo.yaml

```
apiVersion: apps/v1

kind: Deployment

metadata:

  name: udp-echo

  namespace: aic

spec:

  replicas: 1

  selector:

    matchLabels:

      app: udp-echo

  template:

    metadata:

      labels:

        app: udp-echo

    spec:

      containers:

        - name: udp-echo

          image: python:3-alpine

          command: ["python", "-u", "-c"]

          args:

            - |

              import socket

              sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

              sock.bind(('', 9000))

              print("UDP echo server listening on port 9000")

              while True:

                  data, addr = sock.recvfrom(1024)

                  sock.sendto(data, addr)

          ports:

            - containerPort: 9000

              protocol: UDP

---

apiVersion: v1

kind: Service

metadata:

  name: udp-echo

  namespace: aic

spec:

  selector:

    app: udp-echo

  ports:

    - name: udp

      port: 9000

      targetPort: 9000

      protocol: UDP
```

将配置应用到集群：

```
kubectl apply -f udp-echo.yaml
```

## 启用网关 Stream 代理[​](#启用网关-stream-代理 "启用网关 Stream 代理的直接链接")

下面的命令为全新评估环境中的 release 添加监听器。使用 `[0]` 覆盖会替换整个监听器列表；`--reuse-values` 不会将其追加到现有列表。

如果 release 已有监听器，请导出其完整 values，将新监听器追加到列表中，然后使用 `-f stream-values.yaml` 升级，而不要使用下面的数组覆盖方式。请保持命名空间和已安装 Chart 版本不变：

```
helm get values -n aic <release-name> --all -o yaml > stream-values.yaml
```

升级网关，启用 Stream 模式并设置 UDP 监听端口 `9300`：

* APISIX 网关
* API7 网关

运行 `helm list -n aic`，从已安装 Release 的 `CHART` 列取得版本，并去掉 `apisix-` 前缀。

```
helm upgrade -n aic apisix apisix/apisix \

  --version <installed-chart-version> \

  --reuse-values \

  --set "service.stream.enabled=true" \

  --set "service.stream.udp[0]=9300"
```

请使用 `helm list -n aic` 输出中已安装 release 的 `CHART` 列版本，并去掉 `gateway-` 前缀。不要使用 `APP VERSION`，因为它标识的是应用版本而不是 Chart 版本。

```
# 将 3.10.16 替换为已安装的 Chart 版本。

GATEWAY_CHART_VERSION=3.10.16

helm upgrade -n aic api7-ee-3-gateway api7/gateway \

  --version "$GATEWAY_CHART_VERSION" \

  --reuse-values \

  --set "gateway.stream.enabled=true" \

  --set "gateway.stream.only=false" \

  --set "gateway.stream.udp[0]=9300"
```

## 配置 UDP 路由[​](#配置-udp-路由 "配置 UDP 路由的直接链接")

本节将配置一个路由，用于监听 `9300` 端口上的 UDP 流量。

* Gateway API
* APISIX CRD

更新 Gateway manifest 文件，定义用于 UDP 流量的监听器：

gateway.yaml

```
apiVersion: gateway.networking.k8s.io/v1

kind: Gateway

metadata:

  namespace: aic

  name: apisix

spec:

  gatewayClassName: apisix

  listeners:

  - name: http

    protocol: HTTP

    port: 80

  - name: udp

    protocol: UDP

    port: 9300

    allowedRoutes:

      kinds:

      - kind: UDPRoute

  infrastructure:

    parametersRef:

      group: apisix.apache.org

      kind: GatewayProxy

      name: apisix-config
```

创建 Kubernetes manifest 文件，定义 UDPRoute：

udp-route.yaml

```
apiVersion: gateway.networking.k8s.io/v1

kind: UDPRoute

metadata:

  name: stream-route-udp

  namespace: aic

spec:

  parentRefs:

  - name: apisix

    sectionName: udp

  rules:

  - backendRefs:

    - name: udp-echo

      port: 9000
```

当 `listener_port_match_mode` 为 `explicit` 或 `auto` 时，`sectionName: udp` 引用会为 `9300` 添加 `server_port` 匹配。Gateway 监听器端口必须等于网关实际的 stream 监听端口。模式设为 `off` 时，控制器不会添加该匹配。

将配置应用到集群：

```
kubectl apply -f gateway.yaml -f udp-route.yaml
```

创建定义四层路由（stream route）的 Kubernetes manifest 文件：

udp-route.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  name: stream-route-udp

  namespace: aic

spec:

  ingressClassName: apisix

  stream:

    - name: stream-route-udp

      protocol: UDP

      match:

        ingressPort: 9300

      backend:

        serviceName: udp-echo

        servicePort: 9000
```

将配置应用到集群：

```
kubectl apply -f udp-route.yaml
```

## 设置上游传输协议[​](#set-the-upstream-transport "设置上游传输协议的直接链接")

将后端 scheme 设为 `udp`。L4 scheme 仅适用于 stream route。

* Gateway API
* APISIX CRD

将 `BackendTrafficPolicy` 挂载到后端 Service：

udp-upstream-policy.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: BackendTrafficPolicy

metadata:

  name: udp-echo-transport

  namespace: aic

spec:

  targetRefs:

  - group: ""

    kind: Service

    name: udp-echo

    sectionName: udp

  scheme: udp
```

应用策略：

```
kubectl apply -f udp-upstream-policy.yaml
```

创建与后端 Service 同名的 `ApisixUpstream`：

udp-upstream.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  name: udp-echo

  namespace: aic

spec:

  ingressClassName: apisix

  scheme: udp
```

应用上游配置：

```
kubectl apply -f udp-upstream.yaml
```

如需将 stream 插件挂载到 UDPRoute，请参阅[将插件应用到 L4 路由](https://docs.apiseven.com/ingress-controller/apply-plugins-to-l4-routes.md)。

## 验证[​](#验证 "验证的直接链接")

`kubectl port-forward` 仅支持 TCP，无法验证 UDP 代理。请在集群内运行一个临时 Pod，向网关发送 UDP 数据包：

```
kubectl run -it --rm test-udp-proxy --image=busybox --namespace=aic -- /bin/sh
```

进入 Pod 后，执行以下命令向网关发送 UDP 数据包：

```
echo "UDP Testing" | nc -u -w1 <gateway-service-name> 9300
```

你应看到消息 `UDP Testing` 被原样返回。
