Centos7配置Django+Gunicorn+Nginx

环境配置:

  • 我这里用的是Django==1.11.6,Gunicorn==19.7.1。安装gunicorn的时候,注意先安装下面的依赖:
$ pip install greenlet  # Required for both
$ pip install eventlet  # For eventlet workers
$ pip install gevent    # For gevent workers
  • 还有Gevent also requires that libevent 1.4.x or 2.0.4 is installed。
  • 关于gunicorn不明白的地方,推荐直接去看官方文档,说的很详细。

关于Django和Gunicorn的配置:

  • 在跟settins.py同级,创建gunicorn-config.py
# -*- coding: utf-8 -*-
import os
from multiprocessing import cpu_count
# The socket to bind
bind = ["127.0.0.1:9000"]
# The number of worker processes for handling requests.
workers = cpu_count() * 2
# The type of workers to use.
worker_class = "gevent"
# Front-end’s IPs from which allowed to handle set secure headers. (comma separate).
forwarded_allow_ips = '*'

# The number of seconds to wait for requests on a Keep-Alive connection.
keepalive = 6
# Workers silent for more than this many seconds are killed and restarted.
timeout = 65
graceful_timeout = 10
# The maximum number of simultaneous clients.
# This setting only affects the Eventlet and Gevent worker types.
worker_connections = 65535
  • 在manage.py同级目录下,创建一个名为start.sh的shell脚本,方便我们运行gunicorn。-c是加载我们写好的配置文件。foo.wsgi是Django自带的wsgi
#!/bin/bash 
gunicorn -c AbeBetter/gunicorn-config.py AbeBetter.wsgi
  • 比如,AbeBetter是我的Django项目。部分结构如下:
    AbeBetter/
    ├── AbeBetter
    │ ├── gunicorn-config.py
    │ ├── init.py
    │ ├── pycache
    │ ├── settings.py
    │ ├── urls.py
    │ └── wsgi.py
    ├── manage.py
    ├── requirements.txt
    ├── start.sh
  • Django的debug若设置成false,可能造成静态文件无法访问的情况。可以先执行python manage.py collectstatic,则会将静态文件打包在settings.py里设置的STATIC_ROOT的目录下。

关于Nginx的配置:

  • 这里仅列出了比较简单的配置(可以参考Gunicorn官方文档中,关于Nginx的配置部分。Deploying Gunicorn。)
    vim /etc/nginx/nginx.conf
server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        # server_name _;
        server_name localhost;
        # root /usr/share/nginx/html;
        root         /root/AbeBetter;
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                # enable this if and only if you use HTTPS
                # proxy_set_header X-Forwarded-Proto https;
                proxy_set_header Host $http_host;
                # we don't want nginx trying to do something clever with
                # redirects, we set the Host: header above already. 
                proxy_redirect off;
                proxy_pass http://127.0.0.1:9000;
        }
        ······
 }

你可能感兴趣的:(Nginx,django)