代理传输层 (L4) 流量
默认情况下,APISIX 作为应用层 (L7) 代理运行。APISIX 还支持处理传输层 (L4) TCP 和 UDP 流量,既可以单独处理,也可以在处理应用层 (L7) 流量的基础上处理。
本指南将向 你展示如何配置 APISIX 以代理传输层 (L4) 流量,并配置 流路由 以建立与 MySQL 服务器的连接。
前置条件
- 安装 Docker。
- 安装 cURL 以向服务发送请求进行验证。
- 按照 快速入门教程 在 Docker 或 Kubernetes 中启动一个新的 APISIX 实例。
- 安装 MySQL Shell 以启动与 MySQL 服务器的连接。
启动 MySQL 服务器
启动一个 MySQL 实例作为示例上游服务,并将 root 密码配置为 my-secret-pw:
docker run -d \
--name mysql \
--network=apisix-quickstart-net \
-e MYSQL_ROOT_PASSWORD=my-secret-pw \
mysql:9.4
启用传输层 (L4) 代理
默认情况下,APISIX 仅启用应用层 (L7) 代理。要同时代理传输层 (L4) 流量,请配置 proxy_mode 和 stream_proxy。
更新 config.yaml 配置文件 如下:
docker exec apisix-quickstart /bin/sh -c "echo '
apisix:
enable_control: true
control:
ip: 0.0.0.0
port: 9092
proxy_mode: http&stream
stream_proxy:
tcp:
- 9100
# You can configure additional ports or port ranges.
# - 9200
# - "9300-9310"
# udp:
# - 9400
# - "9500-9510"
deployment:
role: traditional
role_traditional:
config_provider: etcd
admin:
admin_key_required: false
allow_admin:
- 0.0.0.0/0
plugin_attr:
prometheus:
export_addr:
ip: 0.0.0.0
port: 9091
' > /usr/local/apisix/conf/config.yaml"
❶ proxy_mode:同时接受传输层 (L4) 和应用层 (L7) 流量。
❷ stream_proxy:配置传输层 (L4) 代理的接口。
重新加载 APISIX 以使配置更改生效:
docker exec apisix-quickstart apisix reload
如果你使用 快速入门 在 Docker 中启动 APISIX,端口 9100 已经映射 (-p 9100:9100)。
创建流路由
创建一个 流路由 并配置 MySQL 服务器作为上游服务。
curl "http://127.0.0.1:9180/apisix/admin/stream_routes" -X PUT -d '
{
"id": "stream-route-mysql",
"server_port": 9100,
"upstream": {
"nodes": {
"mysql:3306": 1
},
"type": "roundrobin"
}
}'
验证
以 root 身份连接 MySQL 服务器,并在提示时输入密码 my-secret-pw:
mysql --host=127.0.0.1 --port=9100 -u root -p
如果成功,你应该看到类似以下的欢迎文本:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 9.4.0 MySQL Community Server - GPL
Copyright (c) 2000, 2025, Oracle and/or its affiliates.
下一步
APISIX在接受下游客户端请求或代理到上游服务时,还支持TLS在TCP连接上作为传输层(L4)代理. 关于相关的TLS和流路由概念,见SSL证书和Stream Routes.