基于Nginx和uWSGI在Ubuntu上部署Django项目

时间:2022-06-24 21:22:57

前言:

对于做Django web项目的童鞋,重要性不言而喻。

参考:https://www.cnblogs.com/alwaysInMe/p/9096565.html

   https://blog.csdn.net/yjdlailin/article/details/50879449

一、几条命令

# 查看是否有 uwsgi 相关的进程
ps -aux|grep "uwsgi"    或者 ps -ef|grep uwsgi
 
# 杀死有关 uwsgi 相关的进程
pkill -9 uwsgi
 

二、安装环境

安装python

安装uwsgi

用python的pip安装最简单:
apt-get install python-dev #不安装这个,下面的安装可能会失败
pip install uwsgi

安装nginx

apt-get install nginx

三、配置nginx和uwsgi配置

uwsgi配置

[uwsgi]
# socket协议,和下面http任意存在一个就可以了
# 使用http协议,监听端口,可以是 :8001(比socket多了一层封装)
http = :8001
#the local unix socket file than commnuincate to Nginx
# 这里的:8001在nginx中也有用到
socket = :8001
# the base directory (full path)
chdir = /path/to/your/project
# Django's wsgi file
wsgi-file = /path/to/your/project/wsgi.py
# maximum number of worker processes
# 该项目使用的进程数,一般使用电脑的 核数
processes = 4
#thread numbers startched in each worker process
threads = 2
# 指定静态文件
static-map=/static=path/to/static
 
#monitor uwsgi status
stats = 127.0.0.1:9191
# clear environment on exit
vacuum   = true

pidfile = path/to/logs/uwsgi.pid
daemonize = path/to/logs/uwsgi.log 

nginx配置

user  nginx;
worker_processes  5;

#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {

upstream django {
    server 127.0.0.1:8001;
}

    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;
    error_log  logs/error.log;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  1800;

    #gzip  on;

    server {
        listen       80;    # 80 是http默认的端口, 443 是https默认的端口(网页一般使用这两个端口)
        server_name  your server name;    # 你访问的路径前面的url名称

        #charset koi8-r;
        charset utf-8;
        client_max_body_size 5000M;

        #access_log  logs/host.access.log  main;

        location / {
            include uwsgi_params; 
            uwsgi_connect_timeout 30;
            uwsgi_pass django;    # 如果上面写别名了,那么,这里还可以直接使用别名
        }

       location /static {
            alias path/to/static/;
       }

        location /media {
            alias path/to/media/;
        }
        error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

四、修改Django配置

# 将debug模式改成False
DEBUG = False
 
# 允许访问的 host, 可以写成单独的 host, 也可以直接写 "*",代表全部
ALLOWED_HOSTS = ['*', ]
 
STATIC_URL = '/static/'
 
# 修改 静态文件的位置
if DEBUG:
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "static"),
    )
else:
    STATIC_ROOT = 'path/to/static'

MEDIA_URL = '/media/'
if DEBUG:
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
else:
    MEDIA_ROOT = 'path/to/media'

  

五、基于uwsgi和nginx部署Django

1.原理

the web client <-> the web server(nginx) <-> the socket <-> uwsgi <-> Django

2.基本测试

测试uwsgi是否正常

在django项目的根目录下创建test.py文件,添加源码如下:

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

然后,Run uWSGI:

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

参数含义:

  • http :8000: 使用http协议,8000端口
  • wsgi-file test.py: 加载指定文件 test.py

打开下面url,浏览器上应该显示hello world

http://example.com:8000

如果显示正确,说明下面3个环节是通畅的:

the web client <-> uWSGI <-> Python

测试Django项目是否正常

首先确保project本身是正常的:

python manage.py runserver 0.0.0.0:8000

如果没问题,使用uWSGI把project拉起来:

uwsgi --http :8000 --module mysite.wsgi

参数含义:

  • module mysite.wsgi: 加载wsgi module

如果project能够正常被拉起,说明以下环节是通的:

the web client <-> uWSGI <-> Django

六、收集静态文件

python manage.py collectstatic

这条命令会将所有 Django 项目的静态文件搜集到上面配置中的,静态文件的位置

七、启动服务

启动nginx

sudo service nginx start

启动uwsgi

uwsgi uwsgi.ini

附:

# 启动nginx    sudo service nginx start
# 停止nginx    sudo service nginx stop
# 重启nginx    sudo service nginx restart