django gunicorn nginx环境部署

gunicorn

简介

Gunicorn 全名叫(Green unicorn),来源于Ruby的Unicorn项目,一款Pyhton的WSGI(web server gateway interface) HTTP服务器,采用pre-fork工作模式

安装gunicorn

pip install gunicorn

django

myapp/settings.pyINSTALLED_APPS 加入gunicorn
在项目下新建wsgi.py

1
2
3
4
5
6
#!/usr/bin/env python
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'dct_redis.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

运行gunicorn

命令行方式

1
gunicorn -b 127.0.0.1:8000 --env DJANGO_SETTINGS_MODULE=myapp.settings myapp.wsgi --daemon

可以用浏览器访问测试一下

配置文件方式

配置文件funicorn.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# coding:utf-8
import logging
import logging.handlers
from logging.handlers import WatchedFileHandler
import os
import multiprocessing
bind = '127.0.0.1:8000' #绑定ip和端口号
backlog = 512 #监听队列
chdir = '/data/wwwroot/myapp' #gunicorn要切换到的目的工作目录
timeout = 30 #超时
worker_class = 'gevent' #使用gevent模式,还可以使用sync 模式,默认的是sync模式
workers = multiprocessing.cpu_count() * 2 + 1 #进程数
threads = 2 #指定每个进程开启的线程数
loglevel = 'info' #日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' #设置gunicorn访问日志格式,错误日志无法设置
"""
其每个选项的含义如下:
h remote address
l '-'
u currently '-', may be user name in future releases
t date of the request
r status line (e.g. ``GET / HTTP/1.1``)
s status
b response length or '-'
f referer
a user agent
T request time in seconds
D request time in microseconds
L request time in decimal seconds
p process ID
"""
accesslog = "/data/wwwlogs/gunicorn_access.log" #访问日志文件
errorlog = "/data/wwwlogs/gunicorn_error.log" #错误日志文件
daemon = True #后台运行

安装模块pip install futures pip install gevent
运行gunicorn -c funicorn.py myapp.wsgi --daemon

配置nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
listen 80;
server_name _;
root /data/wwwroot/myapp;
location /static {
expires 30d;
autoindex on;
add_header Cache-Control provate;
alias /data/wwwroot/myapp/static;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器