【问题标题】:Run FastAPI inside docker container在 docker 容器中运行 FastAPI
【发布时间】:2020-12-10 11:31:03
【问题描述】:

我正在一个 Docker 容器中部署一个网络抓取微服务。我使用了 Scrapy,并且正在使用 FastAPI 公开一个 API 调用,该调用将执行爬虫命令。

我以 Ubuntu 为基础创建了一个 docker 容器,并安装了所有必需的依赖项。然后我使用“exec container_name bash”作为运行 FastAPI 服务器命令的入口点。但是如何将服务器作为后台作业运行?

我尝试从 FastAPI docker 映像 (tiangolo/uvicorn-gunicorn-fastapi:python3.6) 构建,但无法启动。

【问题讨论】:

  • 你看过关于使用 docker 部署的快速 api 文档吗? fastapi.tiangolo.com/deployment/docker
  • 一旦你在 bash 中,你需要使用 gunicorn 来执行你的服务器。将您的 dockerfiles 放入您的问题中,没有它我们无法帮助您
  • 另外,您提到现有的 docker 映像“无法启动”。你能写下你得到的错误或错误吗?这部分可能值得调试。

标签: python docker web-scraping scrapy fastapi


【解决方案1】:

我使用了 tiangolo/uvicorn-gunicorn-fastapi:python3.6 映像并在其中安装了我的网络抓取依赖项以及环境变量,并将工作目录更改为可以执行 scrapy crawl mybot 命令的文件夹。

我之前在使用此解决方案时遇到的问题是响应超时,因为我在 API 函数中使用os.popen('scrapy crawl mybot') 作为操作系统进程运行上述scrapy crawl mybot 命令,记录输出,然后返回响应。这不是正确的方法,我知道 - 我会尝试将它作为后台作业运行;但目前这是一种解决方法。

Dockerfile:

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.6

# Install dependencies:
COPY requirements.txt .
RUN pip3 install -r requirements.txt

ENV POSTGRESQL_HOST=localhost
ENV POSTGRESQL_PORT=5432
ENV POSTGRESQL_DB=pg
ENV POSTGRESQL_USER=pg
ENV POSTGRESQL_PWD=pwd
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8

COPY ./app /app

WORKDIR "/app"

FastAPI 端点:

@app.get("/scraper/crawlWeb")
async def scrapy_crawl_web(bot_name):
    current_time = datetime.datetime.now()
    start = current_time.timestamp()
    print("--START JOB at " + str(current_time))
    stream = os.popen(
        'scrapy crawl %s 2>&1 & echo "$! `date`" >> ./scrapy_pid.txt' % bot_name)
    output = stream.read()
    print(output)
    current_time = datetime.datetime.now()
    end = current_time.timestamp()
    print("--END JOB at " + str(current_time))

    return "Crawler job took %s minutes and closed at %s" % ((end-start)/60.00, str(current_time))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2021-12-03
    • 2015-01-19
    相关资源
    最近更新 更多