Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx reverse proxy on unix socket for uvicorn not working

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

Starting uvicorn as usual:

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

Works - I can access http://127.0.0.1/ from my browser.

Starting uvicorn behind nginx:

$ 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.

If I now request http://127.0.0.1/ then:

  • Nginx: Responds with 502 Bad Gateway
  • uvicorn: Responds with WARNING: Invalid HTTP request received.

Hence a connection is established but something is wrong about the configuration.

Any ideas?

like image 599
Raffael Avatar asked Dec 12 '19 14:12

Raffael


People also ask

Can Nginx listen on UNIX socket?

At this point, NGINX listens on port 80 and redirects to TLS port 443. It also listens on UNIX socket.

How do you check if Nginx reverse proxy is working?

To check the status of Nginx, run systemctl status nginx . This command generates some useful information. As this screenshot shows, Nginx is in active (running) status, and the process ID of the Nginx instance is 8539.


1 Answers

You are using the uwsgi module of nginx. Uvicorn exposes an asgi API. Therefore you should use a "reverse proxy" configuration instead of an uwsgi configuration.

You can get more info on the uvicorn documentation: https://www.uvicorn.org/deployment/#running-behind-nginx (see the proxy_pass line)

like image 187
Blusky Avatar answered Oct 17 '22 22:10

Blusky