简体   繁体   English

如何在公开端口的 docker 容器中运行 uvicorn?

[英]How do I run uvicorn in a docker container that exposes the port?

I am developing a fastapi inside a docker container in windows/ubuntu (code below).我正在 windows/ubuntu 的 docker 容器中开发一个 fastapi(代码如下)。 When I test the app outside the container by running python -m uvicorn app:app --reload in the terminal and then navigating to 127.0.0.1:8000/home everything works fine:当我通过在终端中运行python -m uvicorn app:app --reload然后导航到127.0.0.1:8000/home来测试容器外的应用程序时,一切正常:

{
  Data: "Test"
}

However, when I docker-compose up I can neither run python -m uvicorn app:app --reload in the container (due to the port already being used), nor see anything returned in the browser.但是,当我启动 docker-compose 时,我既不能在容器中运行python -m uvicorn app:app --reload (由于端口已被使用),也看不到浏览器中返回的任何内容。 I have tried 127.0.0.1:8000/home, host.docker.internal:8000/home and localhost:8000/home and I always receive:我试过 127.0.0.1:8000/home、host.docker.internal:8000/home 和 localhost:8000/home,我总是收到:

{
   detail: "Not Found"
}

What step am I missing?我错过了什么步骤?

Dockerfile: Dockerfile:

FROM python:3.8-slim

EXPOSE 8000

ENV PYTHONDONTWRITEBYTECODE=1

ENV PYTHONUNBUFFERED=1

COPY requirements.txt .
RUN python -m pip install -r requirements.txt

WORKDIR /app
COPY . /app

RUN adduser -u nnnn --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "-k", "uvicorn.workers.UvicornWorker", "app:app"]

Docker-compose: Docker-compose:

version: '3.9'

services:
  fastapitest:
    image: fastapitest
    build:
      context: .
      dockerfile: ./Dockerfile
    ports:
      - 8000:8000
    extra_hosts:
      - "host.docker.internal:host-gateway"

app.py:应用程序.py:

from fastapi import FastAPI

app = FastAPI()

@app.get("/home") #must be one line above the function fro the route
def home():
    return {"Data": "Test"}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

The issue here is that when you specify host="127.0.0.1" to uvicorn , that means you can only access that port from that same machine.这里的问题是,当您将host="127.0.0.1"指定给uvicorn时,这意味着您只能从同一台机器访问该端口。 Now, when you run outside docker, you are on the same machine, so everything works.现在,当你在 docker 之外运行时,你同一台机器上,所以一切正常。 But since a docker container is (at least to some degree) a different computer, you need to tell it to allow connections from outside the container as well.但是由于 docker 容器(至少在某种程度上)是一台不同的计算机,您需要告诉它也允许来自容器外部的连接。 To do this, switch to host="0.0.0.0" , and then you should be able to access your dockerized API on http://localhost:8000 .为此,请切换到host="0.0.0.0" ,然后您应该能够在http://localhost:8000上访问您的 dockerized API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM