通过Nginx部署Django

2017-12-06  本文已影响0人  吃土的司机

一、概述

django项目需要在正式环境上跑,故需要使用web服务器,这里采用nginx
nginx安装就不多做介绍,这里主要介绍django uwsgi 配置
服务器为内网:192.168.1.10

二、安装uwsgi

通过pip安装uwsgi。

[root@localhost ~]# python3.5 -m pip install uwsgi
[root@localhost ~]# cp /usr/local/python-3.5/bin/uwsgi /usr/local/bin/

测试uwsgi,创建test.py文件:

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]

通过uwsgi运行该文件:

[root@localhost ~]# uwsgi --http :8001 --wsgi-file test.py

访问地址即可看到测试没有问题:


三、django+uwsgi+nginx

首先罗列下项目文件:

testpro/
├── manage.py
├──
nginx_uwsgi.ini
└── testpro
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py

在我们通过Django创建testpro项目时,在子目录myweb下已经帮我们生成的 wsgi.py文件。所以,我们只需要再创建nginx_uwsgi.ini(自定义命名)配置文件即可,当然,uwsgi支持多种类型的配置文件,如xml,ini等。此处,使用ini类型的配置,配置如下:

# myweb_uwsgi.ini file
[uwsgi]

# Django-related settings

socket = :8001

# the base directory (full path)
chdir = /home/zengfl/testpro

# Django s wsgi file
module = testpro.wsgi

# process-related settings
# master
master = true

# maximum number of worker processes
processes = 4

# ... with appropriate permissions - may be needed
# chmod-socket = 664
# clear environment on exit
vacuum = true

接下来,切换到testpro项目目录下,通过uwsgi命令读取nginx_uwsgi.ini文件启动项目:

[root@localhost ~]# cd /home/zengfl/testpro/
[root@localhost testpro]# uwsgi --ini nginx_uwsgi.ini

启动成功即可,如果有报错就要检查报错处理报错问题

现在进行nginx虚拟主机配置:

server {
listen 80;
server_name cmdb.songrongtong.com;
autoindex off;

error_log logs/cmdb/error.log error;
access_log logs/cmdb/access.log main;

client_max_body_size 75M;

location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8001;
uwsgi_read_timeout 2;
}
location /static {
expires 30d;
autoindex on;
add_header Cache-Control private;
alias /home/zengfl/saltops/static/;
}

}

此时重启nginx 即可访问django项目了

上一篇 下一篇

猜你喜欢

热点阅读