我无法通过 docker 容器通过本地主机上 NGINX 上的 Unix 套接字连接在 ASGI + Gunicorn 上运行的应用程序。
假设我在 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 一起,我可以卷曲我已经绑定到的 UNIX 套接字并收到 200 响应。
curl --unix-socket ///tmp/asgi.sock http://localhost/api/v1/items
我认为这意味着我在将流量定向到 http://localhost/api/v1/items 的 NGINX 配置中存在一些差异。
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))