Django 2.0 使用Nginx部署
1.安装uwsgi,uwsgi是python的一个模块:
pip3 install uwsgi
2.进入项目,启动测试:
cd yxhb uwsgi --http 0.0.0.0:8080 --file yxhb/wsgi.py --static-map=/static=static
参数说明:
--http 这个就和runserver一样指定IP 端口
--file 这个文件就里有一个反射,如果你在调用他的时候没有指定Web Server就使用默认的
-- static 做一个映射,指定静态文
3.使用uwsgi配置文件启动django项目:
简单配置参考: [uwsgi] socket = :8000 #此处建议采用socket方式,避免出现504网关超时 # the local unix socket file than commnuincate to Nginx # the base directory (full path) chdir = /webapps/yxhb # Django's wsgi file module=yxhb.wsgi # maximum number of worker processes processes = 2 #thread numbers startched in each worker process threads = 2 #monitor uwsgi status #stats = 127.0.0.1:9191 # clear environment on exit vacuum = true
更多配置参考:
# uwsig使用配置文件启动
[uwsgi]
# 项目目录
chdir=/webapps/yxhb
# 指定项目的application
module=yxhb.wsgi
# 指定sock的文件路径
socket=/webapps/yxhb/uwsgi.sock
# 进程个数
workers=5
pidfile=/webapps/yxhb/uwsgi.pid
# 指定IP端口
http=192.168.2.108:8080
# 指定静态文件
static-map=/static=/webapps/yxhb/static
# 启动uwsgi的用户名和用户组
uid=root
gid=root
# 启用主进程
master=true
# 自动移除unix Socket和pid文件当服务停止的时候
vacuum=true
# 序列化接受的内容,如果可能的话
thunder-lock=true
# 启用线程
enable-threads=true
# 设置自中断时间
harakiri=30
# 设置缓冲
post-buffering=4096
# 设置日志目录
daemonize=/webapps/yxhb/uwsgi.log
4.启动项目:
uwsgi --ini yxhb_uwsgi.ini
5. nginx 配置:
server { listen 80; server_name xx.xxx.com; charset UTF-8; access_log /usr/local/nginx/logs/yxhb.log; error_log /usr/local/nginx/logs/yxhb_error.log; location / { include uwsgi_params; uwsgi_pass 127.0.0.1:8000; } location /static { expires 30d; add_header Cache-Control private; alias /webapps/yxhb/static/; } location /media { expires 30d; add_header Cache-Control private; alias /webapps/yxhb/media/; #media 是图片upload的路径 } }
6. Django admin 静态文件收集:
收集使用的admin或者其他库含有的静态文件 在django项目的settings.py添加如下代码: # 收集app静态文件到项目目录使nginx能访问到 STATIC_ROOT = os.path.join(BASE_DIR, "static") # 执行python manage.py collectstatic STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder" ) 在终端中进入项目目录在终端执行: $ python manage.py collectstatic 将会自动将app中所含有的静态文件自动收集到项目的setting目录下,解决了某些app,比如admin在部署后找不到静态文件的现象
7. QA:
1.Django运行访问项目出现的问题:DisallowedHost at / Invalid HTTP_HOST header: 到项目目录中去修改 setting.py 文件: ALLOWED_HOSTS = ['*'] 2. 504 Gateway Time-out: a.把uwsgi启动时的参数http改成socket b.在nginx.conf加上uwsgi_read_timeout 120;
挫折经历的太少,所以才把一些琐碎的小事看得很重要。经历越少,理由越多,经历越多,理由反而越少

浙公网安备 33010602011771号