【问题标题】:error when running streamline as frontend and FastAPI as backend运行 streamline 作为前端和 FastAPI 作为后端时出错
【发布时间】:2022-10-17 21:51:28
【问题描述】:

我开发了一个机器学习应用程序,以 fastapi 作为后端,streamlit 作为前端,当我运行它时它可以在我的本地机器上运行,我很可能使用在 fastapi 后端运行的 streamlit 生成预测。但是使用 docker ,它们单独工作,我可以使用快速 API 生成预测,并且可以使用 streamlit 查看 UI,但是如果我想在 streamlit UI 上生成预测,则会生成此错误:

ConnectionError: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with URL: /predict (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xffffa808a0d0>: Failed to establish a new connection: [Errno 111] Connection refused'))

错误可能来自哪里?

【问题讨论】:

  • 显示最小的可重现代码。

标签: python docker fastapi streamlit


【解决方案1】:

我有同样的问题。

FastAPI API 在 8108 公开,所以从我使用的流线型前端:

response = requests.post('http://localhost:8108/predict', json=msg)

或者

response = requests.post('http://0.0.0.0:8108/predict', json=msg)

或者

response = requests.post('http://127.0.0.0:8108/predict', json=msg)

每次尝试都失败了。总是同样的错误

ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=8108): Max retries exceeded with url: /predict (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd5b257d240>: Failed to establish a new connection: [Errno 111] Connection refused'))

【讨论】:

  • 仅在 Docker 中失败,因为在我的 EC2 中它运行良好。我使用 Docker Compose 对解决方案进行 dockerize
  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

使用 Docker compose,在 Docker compose 文件中声明的服务将位于同一网络中。

使用 Docker 撰写文件中定义的服务名称在 Python 代码中引用它们。例如:

码头工人撰写文件:

version: '3.8'

services:
  backend:
    build:
      context: ./backend
      dockerfile: ./Dockerfile.dev
    ports:
    - 2000:2000

  frontend:
    build:
      context: ./frontend
      dockerfile: ./Dockerfile.dev
    ports:
    - 8000:8501

流光代码

import requests
import streamlit as st

BASE_URL = "http://backend:2000/"  # Works with Docker compose

if st.button("Give me the version number!"):
    url_suffix = "version_number"
    response = requests.get(BASE_URL + url_suffix)
    with st.spinner("Requesting version number"):
        st.write(response.json())

请注意如何从 Streamlit 应用程序使用 url:http://backend:2000/version_number 将请求发送到 FastAPI 后端。 backend2000 应该与 Docker 撰写文件匹配。

另请参阅:Docker Compose - container receiving connection refused

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多