Django部署
Django 部署方法
这片文章描述了如何部署一个基于Django的web服务器,参考了https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html并进行了精简和补充。
1 Concept
Nginx和uWSGI是非常流行的web服务器部署组件:
Nginx ----开源的、高性能的HTTP服务器、反向代理服务器、IMAP/POP3服务器;
uWSGI ----web服务器,它使用的WSGI协议是一种服务器网关接口,是web服务器和web应用之间的通信规范;
Django ----开放源代码的Web应用框架,由Python写成,采用了MVC的框架模式。
上述组件之间的通信流程如下:
the web client <-> nginx <-> the socket <-> uwsgi <-> Django
2、配置虚拟环境
安装virtualenv ---- pip install virtualenv;
创建虚拟环境 ---- virtualenv env_django;cd env_django;source bin/activate;cd ../
3、安装Django(v1.11.6)
安装 Django ---- pip install Django;
安装git ----yum install git;
下载Django项目 ---- git clone https://github.com/dongguadan/mysite.git;
进入项目目录 ---- cd mysie
4、安装uWSGI(2.0.15)
安装python-dev ---- yum install python-dev.x86_64;
安装uwsgi ---- pip install uwsgi
5、安装nginx(v1.10.2)
安装nginx ---- yum install nginx;
在mysite目录下准备uwsgi_params、mysite_nginx.conf两个文件:
---- cp /etc/nginx/uwsgi_params ./mysite/;
---- 创建mysite_nginx.conf文件并输入下面的内容
# mysite_nginx.conf
# the upstream component nginx needs to connect to
upstream django {
# server unix:///home/projects/mysite/mysite.sock; # for afile 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 / home/projects/mysite/media; # your Django project's media files - amend as required
}
location /static {
alias / home/projects/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 / home/projects/mysite/uwsgi_params; # the uwsgi_params file you installed
}
}
---- 建立软连接,sudo ln -s ~/ home/projects/mysite/mysite_nginx.conf /etc/nginx/conf.d/
6、启动服务器
打开8000、8001端口并启动nginx和uwsgi ---- sudo /sbin/nginx;uwsgi –socket :8001 –module mysite.wsgi;
7、浏览网页
浏览器输入ip:8000,可以看到网页了。
Faq:
1 阿里云界面可以配置开放端口
2 uwsgi 需要python-dev的支持
3 django ALLOWED_HOSTS = ['*'] 开放ip地址
4 新版nginx没有site_enabled这个目录,改为conf.d
5 django+nginx 不一定支持unix socket的方法,可以改为127.0.0.1:port的方法
6 nginx默认是以nginx的权限登陆的,所以访问不到admin权限下的css文件:出现css 403的错误;将nginx的worker启动用户改为admin就可以了
浙公网安备 33010602011771号