我无法通过Unix套接字在localhost上,通过一个运行在ASGI+Gunicorn上的应用程序连接NGINX。这个应用程序正在一个docker容器中运行。
假设我在docker容器中并启动了NGINX:
/usr/sbin/nginx
我可以打开
http://localhost/api/v1/items
并从NGINX得到404,这意味着至少已经运行。通过执行正在运行的docker服务,我可以使用以下命令启动Gunicorn:
gunicorn app.main:app --name asgi --workers 3 --user=root --group=root --bind=unix:///tmp/asgi.sock --log-level=debug --log-file=- -k uvicorn.workers.UvicornWorker -c /gunicorn_conf.py
Gunicorn正确启动,通过另一个exec,我可以curl绑定的UNIX套接字,并收到200响应。
curl --unix-socket ///tmp/asgi.sock http://localhost/api/v1/items
我认为这意味着我在NGINX配置上有一些差异,会导致流量无法正确指向 http://localhost/api/v1/items。
nginx.conf
daemon off;
user nginx;
worker_processes 1;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
access_log /dev/stdout;
upstream asgi {
server unix:/tmp/asgi.sock fail_timeout=0;
}
server {
listen 80;
server_name localhost;
client_max_body_size 4G;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://asgi;
}
}
}
gunicorn_conf.py
import json
import multiprocessing
import os
workers_per_core_str = os.getenv("WORKERS_PER_CORE", "1")
web_concurrency_str = os.getenv("WEB_CONCURRENCY", None)
host = os.getenv("HOST", "unix")
port = os.getenv("PORT", "///tmp/asgi.sock")
bind_env = os.getenv("BIND", None)
use_loglevel = os.getenv("LOG_LEVEL", "info")
if bind_env:
use_bind = bind_env
else:
use_bind = f"{host}:{port}"
cores = multiprocessing.cpu_count()
workers_per_core = float(workers_per_core_str)
default_web_concurrency = workers_per_core * cores
if web_concurrency_str:
web_concurrency = int(web_concurrency_str)
assert web_concurrency > 0
else:
web_concurrency = max(int(default_web_concurrency), 2)
# Gunicorn config variables
loglevel = use_loglevel
workers = web_concurrency
bind = use_bind
keepalive = 120
errorlog = "-"
# For debugging and testing
log_data = {
"loglevel": loglevel,
"workers": workers,
"bind": bind,
# Additional, non-gunicorn variables
"workers_per_core": workers_per_core,
"host": host,
"port": port,
}
print(json.dumps(log_data))