Django生产环境部署
2018-06-13 本文已影响0人
MononokeHime
本文介绍了Django+uwsgi+Nginx部署web项目的生产环境
1.首先要有一个可以正常运行的django项目。在settings.py
中设置
ALLOWED_HOSTS = ['*']
运行django
python manage.py runserver 127.0.0.1:8000
2.pip安装uwsgi。安装完成后,运行uwsgi,查看uwsgi命令是否在可执行路径下。
pip install uwsgi
3.在django项目下新建myuwsgi.ini
文件(任意文件名都可以)
[uwsgi]
# Django-related settings
socket = 127.0.0.1:9090
# the base directory (full path)
chdir = /home/django_project #这里是项目的路径
# Django s wsgi file
module =django_project _name.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
在shell中执行:
uwsgi --ini myuwsgi.ini
此时uwsgi开始监听9090端口
ps:如果实在不想配置nginx的话,单uwsgi就已经能完成部署了(把socket换成http),你可以把Django中的静态文件放到云平台中如七牛等等,这样你的Web也能被正常访问。
4.配置nginx
nginx默认会读取/etc/nginx/nginx.conf
文件中的配置,修改其配置如下:
http {
...
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name 127.0.0.1; # 服务器的ip地址
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media,如果django中没有media,就不要配置
location /media {
alias /home/django_project/media; # your Django project's media files - amend as required
}
location /static {
alias /home/django_project/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
include uwsgi_params; # the uwsgi_params file you installed
uwsgi_pass 127.0.0.1:9090;
}
}
}
重启nginx
nginx -s reload
service nginx restart
大体的流程是:nginx作为服务器最前端,负责接收client的所有请求,统一管理。静态请求由Nginx自己处理。非静态请求通过uwsgi传递给Django,由Django来进行处理,从而完成一次WEB请求。
通信原理是:
the web client <-> the web server(nginx) <->[80] the socket[9090] <-> uwsgi <->调用django wsgi<->Django