【Django】Django web项目部署(Nginx+uwsgi)

1、安装uwsgi

 经过pip安装uwsgi。html

pip install uwsgi

测试uwsgi,建立test.py文件:python

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

经过uwsgi运行该文件。nginx

uwsgi --http :8001 --wsgi- file test .py

经常使用选项:web

http : 协议类型和端口号bash

processes : 开启的进程数量服务器

workers : 开启的进程数量,等同于processes(官网的说法是spawn the specified number ofworkers / processes)app

chdir : 指定运行目录(chdir to specified directory before apps loading)socket

wsgi-file : 载入wsgi-file(load .wsgi file)测试

stats : 在指定的地址上,开启状态服务(enable the stats server on the specified address)spa

threads : 运行线程。因为GIL的存在,我以为这个真心没啥用。(run each worker in prethreaded mode with the specified number of threads)

master : 容许主进程存在(enable master process)

daemonize : 使进程在后台运行,并将日志打到指定的日志文件或者udp服务器(daemonize uWSGI)。实际上最经常使用的,仍是把运行记录输出到一个本地文件上。

pidfile : 指定pid文件的位置,记录主进程的pid号。

vacuum : 当服务器退出的时候自动清理环境,删除unix socket文件和pid文件(try to remove all of the generated file/sockets)

2、安装nginx

sudo apt-get install nginx  #安装

  启动Nginx:

/etc/init .d /nginx start  #启动
/etc/init .d /nginx stop  #关闭
/etc/init .d /nginx restart  #重启

3、Django部署

在咱们用python manager.py startproject myproject建立项目时,会自动为咱们生成wsgi文件,因此,咱们如今之须要在项目目录下建立uwsgi的配置文件便可,咱们采用ini格式:

# myweb_uwsgi.ini file
[uwsgi]
 
# Django-related settings
 
socket = :8000
 
# the base directory (full path)
chdir           = /mnt/myproject
 
# Django s wsgi file
module          = myproject.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
 
daemonize       = /mnt/myproject/uwsgi_log .log
 
pidfile = /mnt/myproject/uwsgi_pid .log

再接下来要作的就是修改nginx.conf配置文件。打开/etc/nginx/nginx.conf文件,http中添加以下内容。

server {
     listen         8099;
     server_name    127.0.0.1
     charset UTF-8;
     access_log      /var/log/nginx/myweb_access .log;
     error_log       /var/log/nginx/myweb_error .log;
 
     client_max_body_size 75M;
 
     location / {
         include uwsgi_params;
         uwsgi_pass 127.0.0.1:8000;
         uwsgi_read_timeout 2;
     }  
     location /static {
         expires 30d;
         autoindex on;
         add_header Cache-Control private;
         alias /mnt/myproject/static/ ;
      }
  }
listen 指定的是nginx 对外的端口号。

server_name  设置为域名或指定的到本机ip。

nginx经过下面两行配置uwsgi产生关联:

include uwsgi_params;  
uwsgi_pass 127.0.0.1:8000; // 必须与uwsgi中配置的端口一致

最后咱们在项目目录下执行下面的命令来启动关闭咱们的项目:

1 #启动
2 uwsgi --ini uwsgi.ini 
3 /etc/init.d/nginx start  
4 
5 #中止
6 uwsgi --stop uwsgi_pid.log
7 /etc/init.d/nginx stop

好了 ,如今咱们能够访问127.0.0.1:8099便可看到咱们本身的项目了

相关文章
相关标签/搜索