8

文件

# main.py:
from fastapi import FastAPI

app = FastAPI()

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

-

# nginx.conf:
events {
    worker_connections 128;
}
http{
    server {
        listen 0.0.0.0:8080;
        location / {
            include uwsgi_params;
            uwsgi_pass unix:/tmp/uvi.sock;
        }
    }
}

-

# Dockerfile
FROM python:3

COPY main.py .

RUN apt-get -y update && apt-get install -y htop tmux vim nginx

RUN pip install fastapi uvicorn

COPY nginx.conf /etc/nginx/

设置

docker build -t nginx-uvicorn:latest .
docker run -it --entrypoint=/bin/bash --name nginx-uvicorn -p 80:8080 nginx-uvicorn:latest

像往常一样启动 uvicorn

$ uvicorn --host 0.0.0.0 --port 8080 main:app

工作 - 我可以从我的浏览器访问http://127.0.0.1/ 。

在 nginx 后面启动 uvicorn

$ service nginx start
[ ok ] Starting nginx: nginx.

$ uvicorn main:app --uds /tmp/uvi.sock
INFO:     Started server process [40]
INFO:     Uvicorn running on unix socket /tmp/uvi.sock (Press CTRL+C to quit)
INFO:     Waiting for application startup.
INFO:     Application startup complete.

如果我现在请求http://127.0.0.1/那么:

  • Nginx:响应 502 Bad Gateway
  • uvicorn:回应WARNING: Invalid HTTP request received.

因此建立了连接,但配置有问题。

有任何想法吗?

4

1 回答 1

11

您正在使用uwsginginx 的模块。Uvicorn 公开了一个asgiAPI。因此,您应该使用“反向代理”配置而不是uwsgi配置。

您可以获取有关 uvicorn 文档的更多信息:https ://www.uvicorn.org/deployment/#running-behind-nginx (见proxy_pass行)

于 2019-12-12T15:17:01.447 回答