如何在APISIX传统模式(etcd管理)下配置Docker启动自动加载路由?
在APISIX传统模式(依赖etcd)下自动加载默认路由的方案
在传统模式下,APISIX依赖etcd存储配置,无法直接像独立模式那样通过apisix.yaml加载路由。要实现启动时自动将路由写入etcd,有以下几种可行方案:
方案1:利用容器启动钩子调用Admin API初始化路由
APISIX容器启动后,只要Admin API就绪,就能通过它创建路由。可以在docker-compose中给APISIX服务添加启动后脚本,或者单独新增一个初始化服务。
步骤:
- 准备初始化脚本(比如
init_routes.sh):
#!/bin/sh # 等待APISIX Admin API就绪 until curl -s http://apisix:9180/apisix/admin/routes -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1'; do echo "Waiting for APISIX Admin API..." sleep 2 done # 发送请求创建路由 curl -X PUT http://apisix:9180/apisix/admin/routes/1 \ -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' \ -H 'Content-Type: application/json' \ -d '{ "uri": "/hello", "upstream": { "type": "roundrobin", "nodes": { "httpbin.org:80": 1 } } }'
- 在docker-compose.yml中选择以下一种方式配置:
方式A:修改APISIX服务的启动命令
services: apisix: image: apache/apisix:latest volumes: - ./init_routes.sh:/usr/local/bin/init_routes.sh - ./config.yaml:/usr/local/apisix/conf/config.yaml command: sh -c "/usr/local/apisix/bin/apisix start && /usr/local/bin/init_routes.sh" # 保留原有ports、depends_on等配置
方式B:新增独立的初始化服务
services: apisix-init: image: curlimages/curl:latest volumes: - ./init_routes.sh:/init_routes.sh command: sh /init_routes.sh depends_on: - apisix networks: - apisix-net # 和APISIX使用同一网络 apisix: # 保留原有APISIX配置 networks: - apisix-net
方案2:预加载etcd初始数据
etcd支持通过指定初始数据的方式,在启动时导入配置。你可以提前准备好APISIX路由对应的etcd键值对,让etcd容器启动时自动加载。
步骤:
- 准备etcd初始数据文件(比如
etcd_initial_data),格式为每行一个键,下一行对应值:
/apisix/routes/1 {"uri":"/hello","upstream":{"type":"roundrobin","nodes":{"httpbin.org:80":1}},"id":"1"}
- 在docker-compose.yml中修改etcd服务配置,挂载数据文件并设置初始化参数:
services: etcd: image: bitnami/etcd:latest volumes: - ./etcd_initial_data:/bitnami/etcd/data/initial_data environment: - ALLOW_NONE_AUTHENTICATION=yes - ETCD_INITIAL_CLUSTER_STATE=new - ETCD_INITIAL_CLUSTER_TOKEN=etcd-cluster-1 - ETCD_NAME=etcd-node-1 # 保留原有ports等配置
注意:不同etcd镜像的初始数据加载路径可能不同,若使用官方etcd镜像,需调整挂载路径和启动参数。
方案3:通过config.yaml启用自动同步配置(APISIX 2.10+)
从APISIX 2.10版本开始,传统模式支持通过config.yaml指定配置文件,启动时自动将文件中的路由、上游等配置同步到etcd。
步骤:
- 创建
apisix_init.yaml文件,定义路由和上游:
routes: - id: 1 uri: /hello upstream: type: roundrobin nodes: "httpbin.org:80": 1
- 修改APISIX的
config.yaml,添加自动加载配置:
deployment: admin: load_configuration_from_file: /usr/local/apisix/conf/apisix_init.yaml
- 在docker-compose.yml中挂载
apisix_init.yaml到APISIX容器:
services: apisix: image: apache/apisix:latest volumes: - ./config.yaml:/usr/local/apisix/conf/config.yaml - ./apisix_init.yaml:/usr/local/apisix/conf/apisix_init.yaml # 保留原有配置
启动后,APISIX会自动将文件中的配置写入etcd,后续配置将由etcd管理。
内容的提问来源于stack exchange,提问作者Abdullah Chaudhry
相关产品推荐
相关产品推荐

