我要在本地运行 python FastAPI,但是当尝试通过容器运行时,浏览器上没有得到任何响应。也没有错误

Vis*_*hal 3 python containers docker fastapi

我能够在本地运行 python FastAPI(连接到本地主机http://127.0.0.1:8000/),但是当我尝试通过容器运行时,在浏览器上没有得到任何响应。也没有错误消息。

main.py 的内容

from typing import Optional
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}
Run Code Online (Sandbox Code Playgroud)

Dockerfile 的内容

FROM python:3.9.5

WORKDIR /code

COPY ./docker_req.txt /code/docker_req.txt

RUN pip install --no-cache-dir --upgrade -r /code/docker_req.txt

COPY ./app /code/app

CMD ["uvicorn", "app.main:app", "--reload", "--host", "0.0.0.0"]
Run Code Online (Sandbox Code Playgroud)

运行容器时在 cmd 上输出:-

docker run --name my-app1 python-fastapi:1.5
INFO:     Will watch for changes in these directories: ['/code']
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [1] using statreload
INFO:     Started server process [7]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
Run Code Online (Sandbox Code Playgroud)

docker_req.txt——

fastapi==0.73.0
pydantic==1.9.0
uvicorn==0.17.4
Run Code Online (Sandbox Code Playgroud)

Rag*_*had 5

在 docker run 之前插入-d以在分离模式下运行容器。尝试运行:

docker run -d --name my-app5 -p 8000:8000 python-fastapi:1.5