大致按照https://tutos.readthedocs.io/en/latest/source/ndg.html上的说明,我运行了一个nginx-gunicorn-django堆栈,并且它已经可靠地运行了几周。在研究如何添加某些东西(用户上传的媒体文件)时,我研究了我的nginx配置,似乎我还没有编辑任何关于gunicorn的内容。在进行任何更复杂的更改之前,我想了解发生了什么。当nginx配置目录树中的任何地方都没有提及gunicorn时,nginx如何将请求转发到gunicorn?
我的主要nginx配置文件如下所示,我认为这是安装中的默认设置:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
而我的gunicorn启动脚本是:
#!/bin/bash
# Based on an example from https://tutos.readthedocs.io/en/latest/source/ndg.html
NAME="makers" # Name of the application (*)
DJANGODIR=/var/www/makers # Django project directory (*)
SOCKFILE=/var/www/makers/run/gunicorn.sock # we will communicate using this unix socket (*)
USER=nginx # the user to run as (*)
GROUP=webdata # the group to run as (*)
NUM_WORKERS=1 # how many worker processes should Gunicorn spawn (*)
DJANGO_SETTINGS_MODULE=makers.settings # which settings file should Django use (*)
DJANGO_WSGI_MODULE=makers.wsgi # WSGI module name (*)
echo "Starting $NAME as `whoami`"
# Activate the virtual environment
cd $DJANGODIR
source /var/www/makers_venv/bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH
# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR
# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec /var/www/makers_venv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--user $USER \
--bind 0.0.0.0:8000
# --bind=unix:$SOCKFILE
答案 0 :(得分:0)
在location
块中的server
指令之一中定义了nginx如何将请求传递到WSGI服务器(即gunicorn),您可以在http
块中包含该指令。在您的/etc/nginx.conf
文件中查看:
http {
# other http settings
.....
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
在所有server
和server
伪指令中,在定义location
的文件中,您可能会看到这样的设置:
server {
...
location / {
...
# if your guincorn is listening to an IP add
proxy_pass http:127.0.0.1:8000
# or if your gunicorn is listening to a unix socket
# proxy_pass http://unix:/var/www/makers/run/gunicorn.sock
}
基于您的gunicorn启动脚本,您的nginx正在通过端口8000上的IP地址将请求传递给gunicorn:
exec /var/www/makers_venv/bin/gunicorn makers.wsgi:application --bind 0.0.0.0:8000
我建议您阅读Understanding the Nginx Configuration File Structure and Configuration Contexts或我的blog,以更好地了解nginx和gunicorn(或WSGI)的工作原理。