本文我来讲解如何使用 APISIX 来代理 PostgreSQL 数据库服务。

初试

最开始我以为很简单,我采用了直接在 APISIX DashBoard 上配置了一条路由,配置好后,连接发现无法成功连接,提示连接失败。

经过仔细的思考,发现 PostgreSQL 是使用 TCP 协议的数据库,不能通过简单的 route 进行配置,必须使用 stream-proxy 进行代理,接下来我们来看看怎么样来进行配置。

stream-proxy

TCP 是许多流行应用程序和服务的协议,例如 LDAP、MySQL 和 RTMP。UDP(用户数据报协议)是许多流行的非事务性应用程序的协议,例如 DNS、系统日志和 RADIUS。

APISIX 可以动态负载平衡 TCP/UDP 代理。在 Nginx 的世界里,我们把 TCP/UDP proxy 称为 stream proxy,APISIX 就遵循了这个说法。

启用 stream-proxy

要开启 APISIX 流代理需要在 APISIX 配置中开启, APISIX 默认是关闭的。

1
2
3
4
5
6
7
8
apisix:
  stream_proxy: # TCP/UDP proxy
    tcp: # TCP proxy address list
      - 9100
      - "127.0.0.1:9101"
    udp: # UDP proxy address list
      - 9200
      - "127.0.0.1:9211"

如果apisix.enable_admin为 true,则 HTTP 和流代理都启用了上述配置。

如果您已将 设置enable_admin为 false,并且需要同时启用 HTTP 和流代理,请将 设置only为 false:

1
2
3
4
5
6
apisix:
  enable_admin: false
  stream_proxy: # TCP/UDP proxy
    only: false
    tcp: # TCP proxy address list
      - 9100

我修改后的配置如下:

1
2
3
4
5
6
7
8
9
apisix:
  node_listen: 9080              # APISIX listening port
  enable_ipv6: false
  port_admin: 9180 # use a separate port
  stream_proxy: # TCP/UDP proxy
    only: false
    tcp: # TCP proxy address list
      - 9100
      - "127.0.0.1:9101"

配置了流代理相关的配置,我们也要配置流代理请求日志,APISIX 也是默认关闭的,需要我们自己开启,具体如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
nginx_config:                     # config for render the template to generate nginx.conf


  stream:
    enable_access_log: true         # enable access log or not, default false
    access_log: logs/access_stream.log
    access_log_format: "$remote_addr [$time_local] $protocol $status $bytes_sent $bytes_received $session_time"
                                            # create your custom log format by visiting http://nginx.org/en/docs/varindex.html
    access_log_format_escape: default       # allows setting json or default characters escaping in variables
    lua_shared_dict:
      etcd-cluster-health-check-stream: 10m
      lrucache-lock-stream: 10m
      plugin-limit-conn-stream: 10m

配置路由

开启了流代理后,接下来需要配置路由,由于 DashBoard 没有提供流代理的配置,我们只能通过接口来创建流路由,来看看我的配置吧:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
 curl http://127.0.0.1:9180/apisix/admin/stream_routes/1 -H 'X-API-KEY: xx' -X PUT -d '
  {
      "server_port": 9100,
      "upstream": {
          "nodes": {
              "xxx:5432": 1
          },
          "type": "roundrobin"
      },
  "plugins": {
          "ip-restriction": {
              "whitelist": [
                  "127.0.0.1",
                  "xx",
  "192.168.1.117"
              ]
          }
      }
  }'

在这个配置里,我通过 9100 端口将数据库代理出去,并添加了 ip-restriction 白名单,只允许特定 ip进行访问。

小结

在本文中,我简单介绍了如何使用 APISIX 来代理数据库 TCP 服务的过程,并添加了白名单来限制 IP 访问,通过 APISIX stream_proxy 我们能很轻松的代理 TCP/UDP 服务。

参考