You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Compose部署后Streamlit前端无法连接FastAPI后端

Docker容器间连接拒绝问题排查

问题场景

部署FastAPI后端与Streamlit前端两个Docker容器,docker-compose.yaml配置如下:

version: '3.9'

services:
  semcity-frontend:
    image: semcity-frontend
    environment:
      - SEMCITY_BACKEND_URL=http://semcity-backend:8003/
    ports:
      - 8004:8004
    networks:
      local:
    depends_on:
      - semcity-backend

  semcity-backend:
    image: semcity-backend
    environment:
      - OPENAI_API_KEY=<api-key-here...>
    ports:
      - 8003:8003
    networks:
      local:

networks:
  local:
    external: true

容器启动正常,但前端通过浏览器发送请求时触发连接拒绝错误:

semcity-semcity-frontend-1  | requests.exceptions.ConnectionError: HTTPConnectionPool(host='semcity-backend', port=8003): Max retries exceeded with url: /qa?question=asd&celex_ids=32015L2366&max_len=300 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f9cb4183950>: Failed to establish a new connection: [Errno 111] Connection refused'))

后端/qa端点代码:

@app.post("/qa")
def submit(question: str, celex_ids: str, max_len: int):
    relevant_celex_ids = celex_ids.split('_')
    paragraphs, scores, celex_ids, article_ids, paragraph_ids = engine.rank_by_relatedness(question, relevant_celex_ids, 10)
    context = create_context(zip(celex_ids, paragraphs, paragraph_ids, article_ids))
    answer = answer_question(context, question)
    return answer

前端请求代码:

BACKEND_URL = os.environ.get('SEMCITY_BACKEND_URL')
url = ('%sqa?question=%s&celex_ids=%s&max_len=%i' %
           (BACKEND_URL, question, '_'.join(celex_ids), max_words))

if st.button('Ask!'):
    res = requests.post(url)

排查思路

  • 确认后端服务是否完全就绪:depends_on仅保证后端容器先启动,不代表服务已可接收请求。进入前端容器执行curl http://semcity-backend:8003/qa,若仍拒绝,说明后端服务未启动完成。可给后端添加健康检查,或在前端实现请求重试逻辑。
  • 检查FastAPI监听地址:FastAPI默认监听127.0.0.1,容器内仅本地可访问,跨容器无法连接。启动命令需指定--host 0.0.0.0,确保服务监听容器所有网卡地址。
  • 验证外部网络有效性:确认local网络存在且两个容器已加入。执行docker network inspect local,查看容器列表是否包含两个服务的容器;若网络不存在,先执行docker network create local创建。
  • 规范请求参数传递方式:后端为POST接口,前端将参数放在URL查询串中虽被FastAPI支持,但易出现编码问题。建议改用requests.post的params参数传递:
    res = requests.post(f"{BACKEND_URL}qa", params={
        "question": question,
        "celex_ids": '_'.join(celex_ids),
        "max_len": max_words
    })
    
  • 测试容器内DNS解析:进入前端容器执行nslookup semcity-backend,确认能解析到后端容器IP。若解析失败,检查Docker网络DNS配置,或直接用后端容器IP访问测试连通性。
  • 查看后端容器日志:执行docker logs semcity-backend,检查是否存在服务启动失败、端口占用等错误,确认FastAPI服务正常运行在8003端口。

内容的提问来源于stack exchange,提问作者Igor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 12:22:11