阿里云百炼国产大模型中转网关私有化部署
为什么需要自己部署中转网关
阿里云百炼提供的大模型API虽然方便,但直接调用公网接口存在延迟、限流和安全隐患。
私有化部署一个中转网关,相当于在自己服务器上架设一道代理,所有请求先经过你的网关,再转发到阿里云百炼。
好处有三:统一管理API密钥、对请求做缓存和限流、通过内网或低延迟线路减少响应时间。
本文专门针对零基础用户,让你照着操作就能跑通。
准备阶段:一台服务器和一个域名
- 服务器:最低配置 2 核 4GB 内存,操作系统建议 Ubuntu 22.04 或 CentOS 7+。需要开放 80 和 443 端口。
- 域名:绑定到服务器 IP,提前做好 A 记录解析。
- 阿里云百炼API密钥:登录阿里云控制台,在“百炼”产品下创建 API Key。
如果已有宝塔面板,后续步骤可以在面板中操作;
本文以纯命令行方式演示,兼容性更广。
分步搭建中转网关
1. 安装 Nginx 并启用 SSL
sudo apt update
sudo apt install nginx certbot python3-certbot-nginx -y
将域名指向你的服务器 IP 后,执行以下命令获取 SSL 证书并自动配置 HTTPS:
sudo certbot --nginx -d yourdomain.com
2. 编写反向代理配置
创建配置文件 /etc/nginx/conf.d/bailei-gateway.conf,写入以下内容(请替换 yourdomain.com 和 your-api-key):
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
location / {
proxy_pass https://dashscope.aliyuncs.com;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Authorization "Bearer your-api-key";
proxy_ssl_server_name on;
proxy_ssl_name dashscope.aliyuncs.com;
}
}
注意:这里的proxy_pass指向阿里云百炼的官方网关(目前是dashscope.aliyuncs.com),你可以在百炼文档中确认最新地址。Authorization中填入你的 API Key,这样客户端调用时不再需要单独携带密钥。
3. 重启 Nginx 并验证
sudo nginx -t
sudo systemctl reload nginx
如果一切正常,访问 https://yourdomain.com 应该能看到 Nginx 默认 404 或 403(因为没有具体的路由)。
没关系,下一步测试具体接口。
4. 测试中转是否可以正常调用模型
使用 curl 测试一个简单的对话模型调用:
curl https://yourdomain.com/api/v1/services/aigc/text-generation/generation \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-turbo",
"input": {"messages": [{"role": "user", "content": "你好"}]}
}'
如果返回正常的 JSON 结果(包含 output.text),说明中转网关已经成功。
如果返回 401,检查 API Key 是否有效;
返回 502 或 503,检查 proxy_pass 地址是否写错。
避坑与常见问题解答
Q1:返回 502 Bad Gateway
大部分情况是 proxy_pass 地址不可达。
先用 curl https://dashscope.aliyuncs.com 测试能否直接从服务器访问;
如果返回 404 属于正常(说明域名可达),如果无法连接请检查服务器 DNS 或防火墙。
Q2:调用时出现跨域错误
如果前端网页直接调用中转网关,需要在 Nginx 配置中添加跨域头:
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
Q3:想限制只有特定 IP 能访问
在 location / 块中添加 allow 你的IP; deny all;。
Q4:如何避免 SSL 证书到期
Certbot 已自动添加定时任务,可以运行 sudo certbot renew --dry-run 手动测试续期是否正常。
验证效果与后续优化
成功调用后,你就可以在本地应用中将 API 地址改为 https://yourdomain.com,不再需要暴露阿里云的原始密钥。
这样所有请求都经过你控制的服务端,方便做流量审计、缓存和限流。
如果你希望进一步优化性能,可以考虑在 Nginx 上启用 proxy_cache,或使用 OpenResty 做更精细的路由。
对于已经跑通基础的你,下一步可以阅读《Nginx 反代百炼大模型的缓存与限流配置》。
遇到其他问题,优先检查 Nginx 错误日志:sudo tail -f /var/log/nginx/error.log。