跳到主要内容

按端口代理 UDP 流量

本文介绍如何通过 Ingress Controller 基于传入端口为 UDP 流量定义路由规则,并使用 UDP echo server 作为示例上游。

前提条件

  1. 完成设置 Ingress Controller 和网关

启动示例上游服务

创建 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 模式并设置 UDP 监听端口 9300

helm upgrade -n aic apisix apisix/apisix \
--set ... \ # add other parameters
--set "service.stream.enabled=true" \
--set "service.stream.udp[0]=9300"

配置 UDP 路由

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

更新 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/v1alpha2
kind: UDPRoute
metadata:
name: stream-route-udp
namespace: aic
spec:
parentRefs:
- name: apisix
sectionName: udp
rules:
- backendRefs:
- name: udp-echo
port: 9000

将配置应用到集群:

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

验证

由于 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 被原样返回。