很大程度上遵循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
nginx如何将请求传递给WSGI服务器(即gunicorn)在location
块中的一个server
指令中定义,该指令包含在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)是如何工作的。