FastAPI+Celery+Redis+Docker Compose测试报错:无法分配请求地址
解决FastAPI+Celery+Redis+Docker Compose部署时构建阶段Redis连接错误及容器启动自动测试问题
问题场景
- 技术栈:FastAPI + Celery + Redis + Docker Compose
- 构建阶段加测试命令报错:在Dockerfile中添加
RUN python3 -m tests.api_tests执行API测试时,抛出OSError: [Errno 99] Cannot assign requested addressRedis连接错误;移除该命令后,API可正常通过浏览器访问 - 核心需求:要在容器启动时自动执行测试,用于Azure等平台部署;此前仅用Dockerfile+FastAPI时测试完全正常
- 中间尝试踩坑:在docker-compose.yml中新增api_test服务后,出现循环输出的问题
原因分析
- 构建阶段无Redis服务:Docker构建过程是完全隔离的环境,此时Compose配置的Redis、Celery等服务都还没启动,测试代码里的Redis连接自然无法建立,导致报错
- api_test服务配置问题:新增测试服务时没处理好服务依赖(比如没等API和Redis完全启动就跑测试),或者启动命令配置不当,导致服务反复重启、输出循环
最终解决方案
通过shell脚本控制启动顺序+修改测试脚本用requests调用API的组合解决问题:
1. 编写启动脚本(entrypoint.sh)
脚本负责先启动API服务,等服务就绪后再执行测试,最后保持服务运行:
#!/bin/sh # 后台启动API服务 uvicorn main:app --host 0.0.0.0 --port 8000 & # 等待服务启动(时间可根据实际调整) sleep 5 # 执行API测试 python3 -m tests.api_tests # 保持服务前台运行,防止容器退出 wait
2. 更新Dockerfile
把脚本复制到容器里,设置为入口点:
# 复制启动脚本并赋予执行权限 COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh # 设置容器启动时执行的脚本 ENTRYPOINT ["/entrypoint.sh"]
3. 修改测试脚本(api_tests.py)
放弃FastAPI的TestClient,改用requests直接发HTTP请求调用API(避免测试时直接依赖内部服务连接):
import requests def test_health_check(): # 用容器内可访问的API地址 response = requests.get("http://localhost:8000/health") assert response.status_code == 200 assert response.json() == {"status": "healthy"} def test_other_endpoint(): # 其他测试用例示例 payload = {"data": "test"} response = requests.post("http://localhost:8000/process", json=payload) assert response.status_code == 200 if __name__ == "__main__": try: test_health_check() test_other_endpoint() print("✅ All API tests passed!") except AssertionError as e: print(f"❌ Test failed: {e}") exit(1)
内容的提问来源于stack exchange,提问作者Tütü
相关产品推荐
相关产品推荐

