Django 的部署可以有很多方式,采用 nginx + uwsgi 的方式是其中比较常见的一种方式。
准备工作
安装所需软件
pip install Django apt-get install nginx pip install uwsgi # 注: 在 Debian/Ubuntu 系统中需要安装 python-dev
基本测试
创建一个 test.py 的文件
# test.py def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] # python3 #return ["Hello World"] # python2
运行 uWSGI
uwsgi --http :8000 --wsgi-file test.py
参数含义: http :8000: 使用http协议 8000端口 wsgi-file test.py: 加载指定文件 test.py 执行 Curl 命令在终端上返回 Hello world
$curl http://172.16.9.110:8000 Hello World
如果返回的是正确的内容,说明下面工作流程的组件是工作的:
the web client <-> uWSGI <-> Python
测试你的 Django 项目 确保你的项目是可以顺利运行的
python manage.py runserver 0.0.0.0:8000
如果没有报错,使用 uWSGI 的方式运行它
uwsgi --http :8000 --wsgi-file mysite.wsgi
通过浏览器访问正常, 说明下面工作流程的组件是工作的:
the web client <-> uWSGI <-> Django
配置 Nginx
# mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///path/to/your/mysite/mysite.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name .example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /path/to/your/mysite/media; # your Django project's media files - amend as required } location /static { alias /path/to/your/mysite/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed } }
Running the Django application with uswgi and nginx
如果上面一切都显示正常,则下面命令可以拉起django application
uwsgi --socket mysite.sock --wsgi-file mysite.wsgi --chmod-socket=664
Configuring uWSGI to run with a .ini file
每次都运行上面命令拉起django application实在麻烦,使用.ini文件能简化工作,方法如下: 在application目录下创建文件mysite_uwsgi.ini
,填入并修改下面内容:
# mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /path/to/your/project # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /path/to/virtualenv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /path/to/your/project/mysite.sock # ... with appropriate permissions - may be needed # chmod-socket = 664 # clear environment on exit vacuum = true
之后使用这个文件运行 uwsgi
uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file
Once again, test that the Django site works as expected.
参考链接
[0] http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html
[1] http://www.jianshu.com/p/e6ff4a28ab5a