可观测性与稳定性 / 系统课时
搭建多服务实验应用
搭建多服务实验应用
本课搭建一个可重复运行的三服务 HTTP 实验应用:请求从 gateway 进入,经 checkout 再到 inventory,形成至少两跳服务调用;同一入口还能稳定制造成功与失败请求,为后续接入 OpenTelemetry、验证上下文传播和错误追踪提供基线。
学习目标
- 用 Docker Compose 启动 gateway、checkout、inventory 三个相互调用的服务。
- 生成结构稳定的正常请求与受控错误请求。
- 通过 HTTP 返回值确认两跳调用链和错误传播已经按预期工作。
定义实验链路
调用链固定为 客户端 → gateway → checkout → inventory。gateway 与 checkout 都只负责调用下一跳;inventory 是终点,并通过查询参数 fail=true 主动返回 500。这样后续加入追踪后,可以直接比较成功链路与错误链路,而不用临时修改代码。

这种结构刻意保持简单:服务间只有同步 HTTP 调用,没有数据库、消息队列和重试逻辑。基线越单纯,后续看到断链、重复 Span 或错误状态异常时,越容易判断问题来自遥测配置而不是业务复杂度。
实现可复用的服务
三个容器共用同一份 FastAPI 代码,通过 SERVICE_NAME 和 NEXT_URL 决定角色。这样只需要维护一个镜像,同时仍能得到三个独立服务实例。
requirements.txt 固定依赖版本:
fastapi==0.141.1
uvicorn==0.52.4
httpx==0.28.1app.py 内容如下:
import os
import httpx
from fastapi import FastAPI, HTTPException
SERVICE_NAME = os.environ["SERVICE_NAME"]
NEXT_URL = os.getenv("NEXT_URL")
app = FastAPI(title=SERVICE_NAME)
@app.get("/health")
async def health():
return {"service": SERVICE_NAME, "status": "ok"}
@app.get("/work")
async def work(fail: bool = False):
# 最后一跳负责制造受控错误,便于后续观察错误追踪。
if SERVICE_NAME == "inventory":
if fail:
raise HTTPException(status_code=500, detail="inventory failure")
return {"service": SERVICE_NAME, "status": "ok"}
if not NEXT_URL:
raise HTTPException(status_code=500, detail="NEXT_URL is required")
try:
async with httpx.AsyncClient(timeout=2.0) as client:
response = await client.get(
f"{NEXT_URL}/work",
params={"fail": str(fail).lower()},
)
except httpx.RequestError as exc:
raise HTTPException(
status_code=503,
detail="downstream unavailable",
) from exc
# 下游失败统一映射为 502,形成清晰的错误传播路径。
if response.status_code >= 400:
raise HTTPException(
status_code=502,
detail=f"{SERVICE_NAME} downstream={response.status_code}",
)
return {"service": SERVICE_NAME, "downstream": response.json()}Dockerfile 负责构建统一镜像:
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN python -m pip install --no-cache-dir -r requirements.txt
COPY app.py .
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8080"]用 Compose 连接三跳服务
compose.yaml 让 inventory 先达到健康状态,再启动 checkout,最后启动 gateway。只有 gateway 暴露到宿主机的 8080,其余服务只在 Compose 网络中通信。
services:
inventory:
build: .
environment:
SERVICE_NAME: inventory
healthcheck:
test:
- CMD
- python
- -c
- import urllib.request; urllib.request.urlopen('http://localhost:8080/health')
interval: 2s
timeout: 1s
retries: 20
checkout:
build: .
environment:
SERVICE_NAME: checkout
NEXT_URL: http://inventory:8080
depends_on:
inventory:
condition: service_healthy
healthcheck:
test:
- CMD
- python
- -c
- import urllib.request; urllib.request.urlopen('http://localhost:8080/health')
interval: 2s
timeout: 1s
retries: 20
gateway:
build: .
environment:
SERVICE_NAME: gateway
NEXT_URL: http://checkout:8080
depends_on:
checkout:
condition: service_healthy
ports:
- "8080:8080"启动环境并等待 gateway 可访问:
docker compose up --build -d >/dev/null 2>&1
curl --retry 10 --retry-connrefused --retry-delay 1 -sS http://localhost:8080/health
printf '\n'预期输出:
{"service":"gateway","status":"ok"}验收正常与错误基线
先发送正常请求。返回体应完整包含 gateway、checkout、inventory 三层结果,这能证明请求确实经过了两次服务间调用。
curl -sS 'http://localhost:8080/work?fail=false'
printf '\n'预期输出:
{"service":"gateway","downstream":{"service":"checkout","downstream":{"service":"inventory","status":"ok"}}}再发送受控错误请求,并同时输出 HTTP 状态码与响应体:
curl -sS -o /tmp/otel-lab-body -w '%{http_code}\n' 'http://localhost:8080/work?fail=true'
cat /tmp/otel-lab-body
printf '\n'预期输出:
502
{"detail":"gateway downstream=502"}这两个请求就是后续遥测实验的固定基线:成功请求应形成完整的跨服务调用链,错误请求则应保留 inventory 的失败以及逐级传播的错误关系。后续无论采用自动埋点还是手工 SDK,都应先保持这套业务代码与请求不变,只改变遥测接入方式,才能把观测差异准确归因到 OpenTelemetry 配置。