uvicorn 的 unix 套接字上的 Nginx 反向代理无法正常工作

2024-04-03

Files:

# 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/

Setup:

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/ 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/ http://127.0.0.1/ then:

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

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

有任何想法吗?


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

您可以在 uvicorn 文档中获取更多信息:https://www.uvicorn.org/deployment/#running-behind-nginx https://www.uvicorn.org/deployment/#running-behind-nginx(参见proxy_pass line)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

uvicorn 的 unix 套接字上的 Nginx 反向代理无法正常工作 的相关文章

随机推荐