APISIX基础
Apache APISIX基础
前言:为什么选择 APISIX?
API 网关就像是所有后端服务的"大门",所有外部请求都要先经过这扇门,再被转发到对应的服务上。
Apache APISIX 是目前最流行的开源云原生 API 网关之一,基于 NGINX 和 LuaJIT 技术,支持:
- 动态配置:改完配置不用重启服务
- 丰富的插件生态:内置 100+ 插件
- 多语言开发:支持 Lua、Go、Python 等
一、核心概念
1.1 核心组件对照表
| 组件名称 | 通俗理解 | 主要作用 |
|---|---|---|
| Route(路由) | 导航地图 | 定义"什么样的请求应该去哪里" |
| Upstream(上游) | 后端服务集群 | 抽象一组后端服务器,支持负载均衡 |
| Service(服务) | 服务模板 | 多个路由共用的配置抽取,避免重复 |
| Consumer(消费者) | API 调用方 | 代表使用 API 的用户或应用,用于鉴权 |
| Plugin(插件) | 功能增强包 | 限流、认证、日志、监控等 |
| etcd | 配置中心 | 保存所有配置,实现多节点同步 |
1.2 一个请求的完整旅程
访问 https://api.example.com/user/123 时,APISIX 内部流程:
1. 请求到达 → APISIX 443 端口接收请求
2. SSL 握手 → 使用配置的证书完成加密握手
3. 路由匹配 → 根据域名、路径、方法找到对应路由
4. 插件执行 → 依次执行认证、限流、日志等插件
5. 负载均衡 → 从上游集群中选择一个健康节点
6. 请求转发 → 将请求转发到选中的后端节点
7. 响应返回 → 后端响应经 APISIX 加密返回给客户端
二、3 种安装方式
2.1 方式一:Docker 一键安装(推荐)
前提条件: 已安装 Docker 20.10+、curl
curl -sL https://run.api7.ai/apisix/quickstart | sh
安装成功输出:
✔ network apisix-quickstart-net created
✔ etcd is listening on etcd-quickstart:2379
✔ APISIX is up
✔ APISIX is ready!
脚本自动完成:创建 Docker 网络、启动 etcd 容器、启动 APISIX 容器
开放端口:
| 端口 | 用途 |
|---|---|
| 9080 | HTTP 代理 |
| 9443 | HTTPS 代理 |
| 9180 | Admin API |
| 9091 | Prometheus 监控 |
验证安装:
curl "http://127.0.0.1:9080" --head | grep Server
# 输出:Server: APISIX/3.16.0
2.2 方式二:Docker Compose 安装(带 Dashboard)
git clone https://github.com/apache/apisix-docker.git
cd apisix-docker/example
docker-compose -p apisix up -d
docker-compose ps
访问 Dashboard:http://127.0.0.1:9000,默认账号 admin / 密码 admin
2.3 方式三:Linux 二进制安装(生产推荐)
# 安装并启动 etcd
# CentOS/RHEL
sudo yum install -y etcd
# Ubuntu/Debian
sudo apt install -y etcd
sudo systemctl start etcd && sudo systemctl enable etcd
# 下载安装 APISIX
wget https://downloads.apache.org/apisix/3.16.0/apisix-3.16.0-linux-amd64.tar.gz
tar -zxvf apisix-3.16.0-linux-amd64.tar.gz
cd apisix-3.16.0
sudo make install
# 初始化并启动
apisix init
apisix start
三、核心功能实战
3.1 实战一:创建第一个路由
目标: 访问 http://127.0.0.1:9080/ip 转发到 http://httpbin.org/ip
curl -i "http://127.0.0.1:9180/apisix/admin/routes/1" -X PUT -d '
{
"uri": "/ip",
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
参数说明:
| 参数 | 说明 |
|---|---|
uri |
匹配路径 |
type: roundrobin |
轮询负载均衡 |
nodes |
上游节点,值为权重 |
测试:
curl "http://127.0.0.1:9080/ip"
# 返回:{"origin": "123.45.67.89"}
3.2 实战二:生产级 HTTPS 域名转发(重点)
前提: 已有域名、域名解析到服务器公网 IP、443 端口已开放
步骤 1:修改端口映射(9443 改为标准 443)
docker rm -f apisix-quickstart
docker run -d \
--name apisix-quickstart \
--network=apisix-quickstart-net \
-p 80:9080 -p 443:9443 -p 9180:9180 -p 9091:9091 \
-e APISIX_DEPLOYMENT_ETCD_HOST='["http://etcd-quickstart:2379"]' \
apache/apisix:3.16.0-ubuntu
# 验证端口
docker ps | grep apisix-quickstart
# 应看到:0.0.0.0:80->9080/tcp, 0.0.0.0:443->9443/tcp
步骤 2:获取免费 SSL 证书
# Ubuntu/Debian
sudo apt install -y certbot
# CentOS/RHEL
sudo yum install -y certbot
# 申请证书(替换为真实域名)
sudo certbot certonly --standalone -d api.yourdomain.com
证书位置:
- 证书:
/etc/letsencrypt/live/api.yourdomain.com/fullchain.pem - 私钥:
/etc/letsencrypt/live/api.yourdomain.com/privkey.pem
步骤 3:挂载证书到容器
docker stop apisix-quickstart
docker run -d \
--name apisix-quickstart \
--network=apisix-quickstart-net \
-p 80:9080 -p 443:9443 -p 9180:9180 -p 9091:9091 \
-v /etc/letsencrypt:/etc/letsencrypt:ro \
-e APISIX_DEPLOYMENT_ETCD_HOST='["http://etcd-quickstart:2379"]' \
apache/apisix:3.16.0-ubuntu
步骤 4:上传证书到 APISIX
CERT=$(sudo cat /etc/letsencrypt/live/api.yourdomain.com/fullchain.pem)
KEY=$(sudo cat /etc/letsencrypt/live/api.yourdomain.com/privkey.pem)
curl -i "http://127.0.0.1:9180/apisix/admin/ssls/1" -X PUT -d "
{
\"cert\": \"${CERT//$'\n'/\\n}\",
\"key\": \"${KEY//$'\n'/\\n}\",
\"snis\": [\"api.yourdomain.com\"]
}"
步骤 5:配置 HTTPS 路由
curl -i "http://127.0.0.1:9180/apisix/admin/routes/2" -X PUT -d '
{
"hosts": ["api.yourdomain.com"],
"uri": "/anything",
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
hosts字段让同一 APISIX 实例可以同时托管多个域名,各自路由到不同后端。
步骤 6:测试
curl -i "https://api.yourdomain.com/anything"
步骤 7:HTTP 自动跳转 HTTPS(生产必须)
curl -i "http://127.0.0.1:9180/apisix/admin/routes/3" -X PUT -d '
{
"uri": "/*",
"hosts": ["api.yourdomain.com"],
"plugins": {
"redirect": {
"uri": "https://$host$request_uri",
"ret_code": 301
}
}
}'
步骤 8:证书自动续期
sudo crontab -e
# 添加(每天凌晨 2 点检查续期):
0 2 * * * certbot renew --quiet --deploy-hook "docker restart apisix-quickstart"
3.3 实战三:独立 Upstream 复用
多个路由共用同一后端时,先创建独立 Upstream,后端地址变更只需改一处。
# 创建上游
curl -i "http://127.0.0.1:9180/apisix/admin/upstreams/1" -X PUT -d '
{
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}'
# 路由通过 upstream_id 引用
curl -i "http://127.0.0.1:9180/apisix/admin/routes/4" -X PUT -d '
{
"hosts": ["api.yourdomain.com"],
"uri": "/get",
"upstream_id": "1"
}'
3.4 实战四:消费者与 key-auth 认证
# 步骤 1:创建消费者
curl -i "http://127.0.0.1:9180/apisix/admin/consumers" -X PUT -d '
{
"username": "user1",
"plugins": {
"key-auth": {
"key": "my-secret-key-123"
}
}
}'
# 步骤 2:路由启用 key-auth
curl -i "http://127.0.0.1:9180/apisix/admin/routes/2" -X PATCH -d '
{
"plugins": {
"key-auth": {}
}
}'
# 步骤 3:验证
# 无 Key → 401
curl -i "https://api.yourdomain.com/anything"
# 正确 Key → 200
curl -i "https://api.yourdomain.com/anything" -H "apikey: my-secret-key-123"
四、常用插件实战
4.1 限流插件
| 插件 | 算法 | 适用场景 |
|---|---|---|
limit-req |
漏桶算法 | 限制每秒请求速率 |
limit-count |
时间窗口计数 | 限制一段时间内总请求数 |
limit-conn |
并发连接数 | 限制同时处理的请求数 |
示例:每分钟最多 10 次请求
curl -i "http://127.0.0.1:9180/apisix/admin/routes/2" -X PATCH -d '
{
"plugins": {
"limit-count": {
"count": 10,
"time_window": 60,
"rejected_code": 429,
"key": "remote_addr",
"policy": "local"
}
}
}'
分布式部署时
policy改为redis,使用 Redis 跨节点共享计数。
4.2 跨域插件(CORS)
curl -i "http://127.0.0.1:9180/apisix/admin/routes/2" -X PATCH -d '
{
"plugins": {
"cors": {
"allow_origins": "https://your-frontend.com",
"allow_methods": "GET,POST,PUT,DELETE,OPTIONS",
"allow_headers": "Content-Type,Authorization",
"expose_headers": "*",
"max_age": 3600,
"allow_credentials": true
}
}
}'
⚠️ 生产环境不要将
allow_origins设为*,只允许信任的域名。
4.3 日志插件(http-logger)
curl -i "http://127.0.0.1:9180/apisix/admin/routes/2" -X PATCH -d '
{
"plugins": {
"http-logger": {
"uri": "http://your-log-server:8080/logs",
"timeout": 3000,
"retry_delay": 1000,
"buffer_duration": 60,
"max_retry_count": 3,
"batch_max_size": 1000,
"concat_method": "json"
}
}
}'
4.4 监控插件(Prometheus)
# 全局启用
curl -i "http://127.0.0.1:9180/apisix/admin/global_rules/1" -X PUT -d '
{
"plugins": {
"prometheus": {}
}
}'
访问指标端点:http://127.0.0.1:9091/apisix/prometheus/metrics
五、常见问题排查
5.1 HTTPS 问题
| 现象 | 排查方向 |
|---|---|
| 证书无效 | snis 与域名是否一致;是否用了 fullchain.pem;证书是否过期 |
| 443 无法访问 | 防火墙/安全组是否开放;sudo lsof -i :443 检查端口占用 |
| HTTP 不跳转 | 跳转路由 hosts 是否正确;路由优先级是否配置 |
5.2 安装失败
# 检查 Docker 状态
systemctl status docker
# 当前用户加入 docker 组(需重新登录生效)
sudo usermod -aG docker $USER
# 检查 etcd 是否运行
docker ps | grep etcd
5.3 路由不生效
# 检查后端连通性(在容器内直接测试)
docker exec apisix-quickstart curl http://httpbin.org/ip
常见原因:
- 请求路径与
uri不完全匹配 - 路由优先级(
priority字段,数字越大优先级越高)未配置 strict_match模式开启导致匹配失败
5.4 查看日志
# 实时错误日志
docker exec -it apisix-quickstart tail -f /usr/local/apisix/logs/error.log
# 实时访问日志
docker exec -it apisix-quickstart tail -f /usr/local/apisix/logs/access.log
六、生产环境注意事项
6.1 安全配置
启用 Admin API 认证(必须):
# /usr/local/apisix/conf/config.yaml
deployment:
admin:
admin_key_required: true
allow_admin:
- 127.0.0.1/32 # 只允许本机访问 Admin API
admin_key:
- name: "admin"
key: "your-strong-admin-key-123456"
role: "admin"
docker exec apisix-quickstart apisix reload
安全加固清单:
6.2 高可用配置
- 多 APISIX 节点:避免单点故障
- 前置负载均衡:在 APISIX 前部署 Nginx 或云厂商 LB
- etcd 集群:生产环境部署 3 或 5 个节点
- 启用健康检查:自动摘除不健康的上游节点
6.3 性能优化
- 调整 worker 进程数(建议等于 CPU 核心数)
- 对不常变化的响应启用
proxy-cache插件 - 根据后端处理能力合理设置限流阈值
- 建立完善的监控和告警体系
七、总结
通过本教程掌握了:
- 3 种安装方式(Docker 一键 / Docker Compose / 二进制)
- 路由和上游的基础配置
- 生产级 HTTPS 域名转发完整流程(含证书申请、自动续期)
- key-auth 身份认证与 Consumer 管理
- 限流、CORS、日志、监控等常用插件
- 常见问题排查方法
- 生产环境安全与高可用最佳实践

浙公网安备 33010602011771号