Nginx 背后的 Uvicorn

Uvicorn behind Nginx

我从 starlette 和 uvicorn 开始。 RHEL8 EC2 服务器运行 Nginx,然后运行 ​​uvicorn。 (最小)应用程序是(注意两个备选行 uvicorn.run(...)):

import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({'hello': 'world'})


app = Starlette(debug=True, routes=[
    Route('/', homepage),
])
if __name__ == '__main__':
    #uvicorn.run(app, port=8000, host='127.0.0.1',uds='/tmp/uvicorn.sock')
    uvicorn.run(app, port=8000, host='127.0.0.1')

/etc/nginx/nginx.conf 看起来像这样:

events{}
http {
  server {
    listen 80;
    client_max_body_size 4G;

    server_name myserver.com;

    location / {
      proxy_set_header Host $http_host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
      proxy_redirect off;
      proxy_buffering off;
      proxy_pass http://uvicorn;
    }

#    location /static {
#      # path for static files
#      root /path/to/app/static;
#    }
  }

  map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
  }

  upstream uvicorn {
    server unix:/tmp/uvicorn.sock;
  }
}

应用启动:

INFO:     Started server process [126715]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:42584 - "GET / HTTP/1.1" 200 OK

并且 curl 产量:

[root@ip-xxx ~]# curl 127.0.0.1:8000
{"hello":"world"}[root@ip-xxx ~]# 

或者,运行 unix 套接字也启动:

[root@ip-xxx tstApp]# python3.7 example.py
INFO:     Started server process [126768]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on unix socket /tmp/uvicorn.sock (Press CTRL+C to quit)

但是,如果我通过 Nginx 连接到我的服务器……没办法:

502 Bad Gateway

所以应用程序、uvicorn 和 Nginx 是 运行,但一切都没有在一起通信。我错过了什么?欢迎任何帮助。提前谢谢。

已编辑:

nginx.service 文件:

[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
#PrivateTmp=true
PrivateTmp=false

[Install]
WantedBy=multi-user.target

在测试期间,禁用 SElinux 可以解决问题。

SELINUX=disabled