《Agent 特调》项目三:Agent 部署与工具接入|第 02 篇|作者:梯度下降的咖啡师 | 8 年 Java 后端(京东、字节)+ 2 年 AI 应用开发
上一节我们把 MCP 服务跑通了,但它只活在 localhost:Claude Desktop 能连,是因为它和你在同一台机器;同事想用,只能把代码拷过去。
这一节把它真正扔到公网:一个域名、一张证书、三个容器。目标很具体——浏览器打开 https://agent.example.com 能聊天,流式输出不卡顿,MCP 服务只对内网开放,服务器重启后自动恢复。
不上一上来就 K8s。一台 2C4G 的云服务器 + Docker Compose,足够把 side project 跑到有真实用户。
01 先定形态:三个容器,一条链路#

图 1:公网只开 80/443,MCP 只走 Compose 内网。
三个原则,先记住:
- 只有 Nginx 暴露端口。api 和 mcp 用
expose,只在 Compose 内网可达,公网访问不到 8000。MCP 不挂公网路由,只让 api 通过 http://mcp:8000 调。 - TLS 在边缘终止。证书只装在 Nginx,应用里不碰证书,换证书不影响业务容器。
- 状态放卷里。SQLite 会话库、上传文件放 named volume;容器可以随时删了重建。
对应到 Compose 是四个服务:nginx、api、mcp,外加一个只在签发证书时跑的 certbot。
02 目录先摆好#
agent-specialty/
├── app/
│ ├── main.py # FastAPI 入口、/health、/chat
│ └── graph.py # 你的 LangGraph
├── mcp/
│ ├── Dockerfile
│ └── mcp_server.py # 上一节的 FastMCP
├── deploy/
│ ├── nginx.bootstrap.conf
│ ├── nginx.full.conf
│ ├── nginx.conf # 当前生效的那份,由上面两个拷贝而来
│ ├── certs/ # Let's Encrypt 证书,git 忽略
│ └── www/ # ACME challenge,git 忽略
├── data/ # 本地调试用;线上用 named volume
├── Dockerfile
├── compose.yaml
├── requirements.txt
└── .env.example
.env 永远不进 git。.gitignore 至少要有:
.env
deploy/certs/
deploy/www/
data/
03 镜像:非 root、能自检#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1
WORKDIR /app
RUN mkdir -p /app/data && chown -R 10001:10001 /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY --chown=10001:10001 app ./app
USER 10001:10001
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
|
几个决定都是有原因的:
- 非 root:容器里被打穿,攻击者拿到的不是 root。
data 目录提前 chown,后面挂 named volume 时权限才对得上。 --workers 1:这一版用 SQLite checkpointer,多个 worker 抢同一个库会锁。要扩到多 worker,先把 checkpointer 换成 Postgres,再谈并发。- healthcheck 用 Python 自检:slim 镜像里没有 curl,用标准库最稳。返回非 200 时
urlopen 会抛异常,健康检查自然失败。 - 依赖版本别靠手写猜:
requirements.txt 里先写包名,部署前用 pip freeze > requirements.txt 把实际版本固化下来(或在 CI 里生成 lock),别让一次 pip install 把线上版本换了。
04 Compose:内网互通,外网只开 80/443#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| services:
api:
build: .
env_file: .env
expose:
- "8000"
depends_on:
- mcp
restart: unless-stopped
volumes:
- agent_data:/app/data
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)"]
interval: 30s
timeout: 5s
retries: 3
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
mcp:
build: ./mcp
command: ["python", "-m", "mcp_server"]
expose:
- "8000"
restart: unless-stopped
nginx:
image: nginx:1.27-alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./deploy/nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./deploy/certs:/etc/letsencrypt:ro
- ./deploy/www:/var/www/certbot:ro
depends_on:
- api
restart: unless-stopped
certbot:
image: certbot/certbot:latest
profiles: ["certbot"]
volumes:
- ./deploy/certs:/etc/letsencrypt
- ./deploy/www:/var/www/certbot
volumes:
agent_data:
|
注意 certbot 加了 profiles,正常的 docker compose up -d 不会把它拉起来,只有显式 --profile certbot 时才运行。
api 的 depends_on: mcp 只保证启动顺序,不保证 MCP 真的 ready。MCP 没有现成健康端点时,先接受这一点:第一次请求失败就重试,别把启动顺序当成健康检查。
mcp_server.py 里固定用 Streamable HTTP 启动,并且必须监听 0.0.0.0——只监听 127.0.0.1 的话,别的容器连不进来:
1
2
3
4
| if __name__ == "__main__":
mcp.settings.host = "0.0.0.0"
mcp.settings.port = 8000
mcp.run(transport="streamable-http")
|
mcp/Dockerfile 比业务镜像简单,只装 SDK 和入口:
1
2
3
4
5
6
7
8
9
10
11
12
| FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1
WORKDIR /app
RUN pip install "mcp[cli]"
COPY mcp_server.py .
EXPOSE 8000
USER 10001
CMD ["python", "-m", "mcp_server"]
|
服务名 mcp 在 Compose 网络里就是主机名,api 侧配置 http://mcp:8000/mcp 即可。公网不挂 /mcp 路由;如果确实要给外部 Host 用,单独开一个带 token 校验的入口,不要直接把内网端口暴露出去。
05 FastAPI:一个健康检查,一个 SSE 接口#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| import json
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from app.graph import graph
app = FastAPI(title="agent-specialty")
class ChatRequest(BaseModel):
message: str
user_id: str = "demo"
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/chat")
async def chat(body: ChatRequest, request: Request):
async def event_stream():
async for chunk, _meta in graph.astream(
{"messages": [{"role": "user", "content": body.message}]},
config={"configurable": {"thread_id": body.user_id}},
stream_mode="messages",
):
if await request.is_disconnected():
break
token = chunk.content
if not isinstance(token, str) or not token:
continue
payload = json.dumps({"text": token}, ensure_ascii=False)
yield f"event: token\ndata: {payload}\n\n"
yield "event: done\ndata: [DONE]\n\n"
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
|
这段代码有三个关键点:
stream_mode="messages" 拿到的是 token 级增量,不是整段回答。前端才能边收边渲染。request.is_disconnected() 在客户端关页面时停掉生成,别让模型继续烧 token。X-Accel-Buffering: no 是给 Nginx 看的。只配 Nginx 不够,应用侧也声明一次,双保险。
请求体是 JSON,字段少的时候无所谓;等你要加 history、tools、temperature 这些嵌套结构,建议先把样例扔进 ForJSON 里把层级校一遍,比在终端里数括号快。
06 Nginx:TLS、SSE 不缓冲、限流#
先写完整版 deploy/nginx.full.conf:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
| limit_req_zone $binary_remote_addr zone=chat_limit:10m rate=20r/m;
server {
listen 80;
server_name agent.example.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
http2 on;
server_name agent.example.com;
ssl_certificate /etc/letsencrypt/live/agent.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/agent.example.com/privkey.pem;
client_max_body_size 20m;
location /chat {
limit_req zone=chat_limit burst=5 nodelay;
proxy_pass http://api:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
gzip off;
proxy_read_timeout 300s;
}
location / {
proxy_pass http://api:8000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
|
逐个解释容易踩的点:
http2 on; 是 Nginx 1.25.1 之后的写法。老文章里的 listen 443 ssl http2; 在新版本会报 deprecated warning,别照抄。proxy_buffering off + gzip off:SSE 最怕边缘先攒一段再吐。关掉缓冲和压缩,token 才能一条条到浏览器。proxy_read_timeout 300s:Agent 一次回答超过默认 60 秒很常见,不调大会在等模型时被 Nginx 掐断。limit_req:/chat 是最贵的接口,20 次/分钟、burst 5,防的是脚本而不是真人。真被限了会返回 503,前端要能提示“稍后再试”。/mcp 不挂公网:MCP 是服务间调用,不经过 Nginx;以后真要开放给外部 Host,单独加 token 校验和限流,别直接复用这条 /chat 的规则。
第一次签发证书时,Nginx 还不能加载不存在的证书文件。所以先备一份只开 80 的引导配置 deploy/nginx.bootstrap.conf:
1
2
3
4
5
6
7
8
9
10
11
12
| server {
listen 80;
server_name agent.example.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 200 "bootstrap\n";
}
}
|
07 HTTPS:两阶段签发,别一上来就 full#

图 2:HTTPS 两阶段签发。先让 80 端口把证书签下来,再切 443 完整配置。
服务器上先装 Docker 和 Compose 插件,然后把 DNS 的 A 记录指到这台机器。80 和 443 都要通:
1
2
| sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
|
第一阶段:只用 HTTP 启动 Nginx,把证书签下来。
1
2
3
4
5
6
7
8
| cp deploy/nginx.bootstrap.conf deploy/nginx.conf
docker compose up -d nginx
docker compose --profile certbot run --rm certbot certonly \
--webroot -w /var/www/certbot \
-d agent.example.com \
--email you@example.com \
--agree-tos --no-eff-email
|
签发成功会看到证书落在 deploy/certs/live/agent.example.com/。
第二阶段:切到完整配置,重载 Nginx。
1
2
3
4
| cp deploy/nginx.full.conf deploy/nginx.conf
docker compose up -d --build
docker compose exec nginx nginx -t
docker compose exec nginx nginx -s reload
|
nginx -t 必须先过。配置有语法错误时 reload 不会生效,旧进程还在跑,很容易误以为“已经上线了”。
证书 90 天过期,写一个续期脚本 deploy/renew-cert.sh,再让 cron 每月调用一次:
1
2
3
4
5
6
7
8
| #!/usr/bin/env bash
set -euo pipefail
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
cd /home/ubuntu/agent-specialty
docker compose --profile certbot run --rm certbot renew \
--webroot -w /var/www/certbot
docker compose exec nginx nginx -s reload
|
1
2
3
4
| chmod +x deploy/renew-cert.sh
crontab -e
# 每月 1 号 03:15 跑一次
15 3 1 * * /home/ubuntu/agent-specialty/deploy/renew-cert.sh >> /home/ubuntu/agent-cert.log 2>&1
|
certbot 只在到期前 30 天真正续,平时跑是空操作,不用心疼。
08 上线验收:别只看容器是 Up#
按顺序跑一遍,任何一步失败就先停:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| # 1. 容器都在,api 是 healthy
docker compose ps
# 2. 应用活着
curl -fsS https://agent.example.com/health
# {"status":"ok"}
# 3. SSE 真的在流,而不是攒完一次吐
curl -N -X POST https://agent.example.com/chat \
-H "Content-Type: application/json" \
-d '{"message":"用一句话介绍你自己","user_id":"smoke-test"}'
# 4. 证书有效期
echo | openssl s_client -servername agent.example.com \
-connect agent.example.com:443 2>/dev/null | openssl x509 -noout -dates
# 5. 日志没有异常堆栈
docker compose logs --tail=100 api
|
第 3 步重点看输出节奏:event: token 应该一条条出现。如果等十几秒后突然一次性刷屏,说明某一层还在缓冲——先查 Nginx 的 proxy_buffering,再查 CDN 或云厂商的 LB。
09 常见坑,按出现频率排#
502 Bad Gateway:九成是 proxy_pass 的主机名写错。Compose 里服务名就是 DNS,api:8000 不是 localhost:8000。先 docker compose logs api 看应用有没有起来,再 docker compose exec nginx getent hosts api 看解析。
SSE 卡住不动:按链路逐层排除——应用返回头有没有 X-Accel-Buffering: no、Nginx 有没有 proxy_buffering off、云厂商 LB 有没有开压缩或缓存。三层任一层缓冲,前端都会表现为“最后一次性出来”。
Nginx 起不来,报找不到 fullchain.pem:就是跳过了引导阶段。先切回 bootstrap 配置启动,签完证书再切 full。
上传文件 413:Nginx 默认 1MB。client_max_body_size 20m 要放在 server 块里,不是 location 里漏配。
容器里写文件 Permission denied:named volume 的属主和镜像里的 app 用户对不上。用 docker compose exec api id 看 UID,再决定是改 Dockerfile 的 chown,还是给 volume 换属主。别直接 chmod 777。
API key 泄露:.env 进 git、或者被 docker build 打进镜像,是最常见的两种。.dockerignore 里加 .env,CI 日志里也别 echo。
磁盘被日志吃满:Compose 已经限制 max-size: 10m、max-file: 3;没用 Compose 的容器要单独配,否则 json-file 默认可以无限长。
时区不对:容器默认 UTC,日志和定时任务会差 8 小时。Compose 里给 api 加 TZ=Asia/Shanghai,或者在 .env 里统一。
10 这一节交付了什么#
现在这套东西能跑:
- 一个域名,HTTPS 自动续期;
/chat 的 SSE 不被缓冲,前端能逐字渲染;- MCP 只在 Compose 内网,公网只能打到 Nginx;
- 容器挂了自动重启,日志有上限,数据在 named volume;
- 一条
docker compose up -d --build 就能重建。
它还不是生产级:没有登录鉴权、没有多副本、没有集中日志、没有告警、没有灰度。/chat 是公开接口,只靠 Nginx 限流挡不住刷子;公网前至少加一层 token 或网关,FastAPI 的 /docs 也建议用 FastAPI(docs_url=None) 关掉。等有真实流量,再按瓶颈加,而不是提前把 K8s 供起来。
下一篇换到质量侧:项目四 01|给知识库 Agent 做评测:检索命中率、答案忠实度和回归集。部署完只是开始,你得知道它答得对不对。关注「梯度下降的咖啡师」不迷路,完整代码和系列教程见 gradcoffee.com,GitHub 仓库地址见博客首页置顶。
互动两问:
- 你现在把 Agent 部署在哪:本机、云服务器,还是 Serverless?
- 上线后你最担心的是成本、延迟,还是答错?
作者:8 年 Java 后端(京东、字节)+ 2 年 AI 应用开发,写「梯度下降的咖啡师」,记录从大厂后端到 AI 应用开发的实战踩坑。