• Django项目使用uwsgi+nginx部署上线


    前言

    代码已经开发完成,正式部署上线

    settings 配置

    DEBUG = False
    ALLOWED_HOSTS = ['*']
    ...
    # 静态资源
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [ BASE_DIR / 'StaticFiles']
    STATIC_ROOT = os.path.join(BASE_DIR, 'Allstatic')
    # or
    # STATIC_ROOT = BASE_DIR / 'Allstatic'  # 资源部署
    
    # 媒体资源
    MEDIA_URL = '/media/'
    MEDIA_ROOT = BASE_DIR / 'media'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    python manage.py collectstatic  # 按照 STATIC_ROOT 收集静态文件
    
    • 1
    项目下urls.py
    from django.contrib import admin
    from django.urls import path, include, re_path
    from rest_framework.documentation import include_docs_urls
    from django.views.static import serve
    from django.conf import settings
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        ...
        # django改为上线模式后,不再提供静态文件服务,需要添加静态资源的路由信息
        re_path('static/(?P.*)', serve, {'document_root': settings.STATIC_ROOT}, name='static')
        # 定义媒体资源的路由信息
        re_path('media/(?P.*)', serve, {'document_root': settings.MEDIA_ROOT}, name='media'),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    1、安装uwsgi 和配置uwsgi

    安装uWSGI
    pip3 install uwsgi
    测试uWSGI是否安装成功
    在终端中输入以下命令查看uwsgi的版本号,如果输出正常,说明uswgi已安装成功
    $ uwsgi --version
    2.0.15
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    如果想要运行项目来测试
    
    # uwsgi --http :8000 --chdir 项目路径 -w 项目.wsgi 静态文件地址--static-map=/static=static
    
    uwsgi --http :8000 --chdir /home/teacher/ -w teacher.wsgi --static-map=/static=static
    
    • 1
    • 2
    • 3
    • 4
    • 5

    推荐配置文件启用wsgi

    不使用nginx的配置(不推荐)

    uwsgi.ini
    [uwsgi]
    # 项目绝对路径
    chdir = /home/cooper/projects/foo/web1
    # 监听的端口,当没有nginx时使用这个
    http = 0.0.0.0:8000
    # 静态资源代理  映射目录,实际静态目录
    static-map = /static= /home/cooper/projects/foo/web1/Allstatic
    # 主应用中的wsgi文件
    wsgi-file = /home/cooper/projects/foo/web1/web1/wsgi.py
    
    # 启动一个master进程来管理其他的子进程
    master = True
    # 开启四个进程
    processes = 4
    # 两个线程
    thread = 2
    # 设置每个工作进程处理请求上限,达到上限时,将回收/重启,可预防内存泄漏
    max-request = 5000
    # 服务停止时自动移除unix socket和pid 文件
    vacuum = True
    
    # uwsgi 日志
    #daemonize = /root/Server/logs/uwsgi.log
    logto = /home/cooper/projects/foo/web1/logs/ty_log.log  # 需要创建logs文件夹
    # 日志格式化
    logformat = %(ltime) | pid:%(pid) wid:%(wid) | %(proto) %(status) | %(method) | %(host)%(uri) | request_body_size:%(cl) | response_body_size:%(rsize)
    
    # 服务的pid记录文件
    pidfile = uwsgi.pid
    
    # 指定虚拟环境 绝对地址到bin文件夹前
    # virtualenv = /home/venv
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    使用nginx的配置

    uwsgi.ini
    [uwsgi]
    # 项目绝对路径
    chdir = /home/cooper/projects/foo/web1
    ;套接字方式的IP地址:端口号【此模式需要有nginx,如果只用uwsgi的话可以忽略此项】
    ;socket=0.0.0.0:8000
    # 主应用中的wsgi文件
    wsgi-file = /home/cooper/projects/foo/web1/web1/wsgi.py
    
    # 启动一个master进程来管理其他的子进程
    master = True
    # 开启四个进程
    processes = 4
    # 两个线程
    thread = 2
    # 设置每个工作进程处理请求上限,达到上限时,将回收/重启,可预防内存泄漏
    max-request = 5000
    # 服务停止时自动移除unix socket和pid 文件
    vacuum = True
    
    # uwsgi 日志
    #daemonize = /root/Server/logs/uwsgi.log
    logto = /home/cooper/projects/foo/web1/logs/ty_log.log
    # 日志格式化
    logformat = %(ltime) | pid:%(pid) wid:%(wid) | %(proto) %(status) | %(method) | %(host)%(uri) | request_body_size:%(cl) | response_body_size:%(rsize)
    
    # 服务的pid记录文件
    pidfile = uwsgi.pid
    
    # 指定虚拟环境 绝对地址到bin文件夹前
    # virtualenv = /home/venv
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    2、安装 nginx和配置

    yum install nginx -y  安装
    
    systemctl start nginx   启动
    systemctl stop nginx   停止
    systemctl status nginx  查看状态
    systemctl restart nginx  重启
    systemctl enable nginx  开机自启动
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    niginx 配置

    安装nginx后,默认的配置文件在
    /etc/nginx/nginx.conf
    修改nginx.conf
    
    
    • 1
    • 2
    • 3
    • 4
    基本配置
    # For more information on configuration, see:
    #   * Official English Documentation: http://nginx.org/en/docs/
    #   * Official Russian Documentation: http://nginx.org/ru/docs/
    
    user root;    # 用户名
    worker_processes auto;
    error_log /var/log/nginx/error.log;
    pid /run/nginx.pid;
    
    # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
    include /usr/share/nginx/modules/*.conf;
    
    events {
        worker_connections 1024;
    }
    
    http {
        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  /var/log/nginx/access.log  main;
    
        sendfile            on;
        tcp_nopush          on;
        tcp_nodelay         on;
        keepalive_timeout   65;
        types_hash_max_size 4096;
    
        include             /etc/nginx/mime.types;
        default_type        application/octet-stream;
    
        upstream django {
            server 127.0.0.1:8000;
            }
    
        # Load modular configuration files from the /etc/nginx/conf.d directory.
        # See http://nginx.org/en/docs/ngx_core_module.html#include
        # for more information.
        # include /etc/nginx/conf.d/*.conf;
    
        server {
            listen       80;
            listen       [::]:80;
            # server_name  _;
            # root         /usr/share/nginx/html;
    
            # Load configuration files for the default server block.
            # include /etc/nginx/default.d/*.conf;
    
            location /static {
                alias /home/cooper/projects/foo/web1/Allstatic/;
                }
    
            location / {
                include uwsgi_params;
                uwsgi_pass django;
                }
    
            error_page 404 /404.html;
            location = /404.html {
            }
    
            error_page 500 502 503 504 /50x.html;
            location = /50x.html {
            }
        }
    
    # Settings for a TLS enabled server.
    #
    #    server {
    #        listen       443 ssl http2;
    #        listen       [::]:443 ssl http2;
    #        server_name  _;
    #        root         /usr/share/nginx/html;
    #
    #        ssl_certificate "/etc/pki/nginx/server.crt";
    #        ssl_certificate_key "/etc/pki/nginx/private/server.key";
    #        ssl_session_cache shared:SSL:1m;
    #        ssl_session_timeout  10m;
    #        ssl_ciphers HIGH:!aNULL:!MD5;
    #        ssl_prefer_server_ciphers on;
    #
    #        # Load configuration files for the default server block.
    #        include /etc/nginx/default.d/*.conf;
    #
    #        error_page 404 /404.html;
    #            location = /40x.html {
    #        }
    #
    #        error_page 500 502 503 504 /50x.html;
    #            location = /50x.html {
    #        }
    #    }
    
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    完整配置 (待验证)
    user www-data;
    worker_processes auto;
    pid /run/nginx.pid;
    include /etc/nginx/modules-enabled/*.conf;
    
    events {
        worker_connections 768;
        # multi_accept on;
    }
    
    http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
    
        include /etc/nginx/mime.types;
        default_type application/octet-stream;
    
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;
    
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;
    
        gzip on;
    
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
    
        server {
             listen 80;  # 监听80端口,作为默认服务器
             server_name app4007.acapp.acwing.com.cn;  # 服务器名,可以是域名或IP地址
             rewrite ^(.*)$ https://${server_name}$1 permanent;
        }
    
        server {
            listen 443 ssl;  # 将80端口的HTTP请求重定向到443端口的HTTPS请求,提高安全性,使用SSL证书和协议来保证HTTPS请求的加密和验证
            server_name app4007.acapp.acwing.com.cn;
            ssl_certificate   cert/acapp.pem;
            ssl_certificate_key  cert/acapp.key;
            ssl_session_timeout 5m;
            ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            ssl_prefer_server_ciphers on;
            charset utf-8;
            access_log /var/log/nginx/access.log;
            error_log /var/log/nginx/error.log;
    
            client_max_body_size 10M;
    
            location / {  # 匹配所有请求路径
                include /etc/nginx/uwsgi_params;  # 包含uWSGI的请求参数
                uwsgi_pass 127.0.0.1:8000;  # 转发请求给uWSGI服务器,由Django应用程序处理
                uwsgi_read_timeout 60;  # 设置uWSGI的读取超时时间
            }
            location /static {  # 匹配以'/static'开头的请求路径,将以'/static'开头的请求直接返回静态文件内容,提高效率
                alias /home/asanosaki/djangoapp/static/;  # 指定静态文件存放的目录
            }
            location /wss {  # 匹配以'/wss'开头的请求路径,将以'/wss'开头的请求转发给WebSocket服务器,实现双向通信
                proxy_pass http://127.0.0.1:5015;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header Host $http_host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    3、运行

    systemctl start nginx
    进入到虚拟环境后(按需)
    找到uwsgi.ini的配置文件
    uwsgi --ini uwsgi.ini &   加上 & 表示后台运行
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    脚本运行

    启动脚本reboot.sh

    #!/usr/bin/env bash
    
    echo -e "\033[34m---------------------wsgi process------------------------------\033[0m"
    
    ps ef|grep uwsgi.ini | grep -v grep
    
    sleep 0.5
    
    echo -e "\n---------------------------going to close----------------------------------"
    
    ps -ef | grep uwsgi.ini | grep -v grep | awk '{print $2}' | xargs kill -9
    
    sleep 0.5
    
    echo -e "\n----------------------check if the kill action is correct----------------------------"
    
    /root/.cache/pypoetry/virtualenvs/foo-bXHpp0ED-py3.9/bin/uwsgi   --ini wx_uwsgi.ini & >/dev/null
    
    echo -e "\n\033[42;1m------------------------started-------------------------\033[0m"
    
    sleep 1
    
    ps ef | grep uwsgi.ini | grep -v grep
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    停止脚本 stop.sh

    #!/usr/bin/env bash
    
    echo -e "\033[34m---------------------wsgi process------------------------------\033[0m"
    
    ps ef|grep uwsgi.ini | grep -v grep
    
    sleep 0.5
    
    echo -e "\n---------------------------going to close----------------------------------"
    
    ps -ef | grep wx_uwsgi.ini | grep -v grep | awk '{print $2}' | xargs kill -9
    
    sleep 0.5
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    参考资料

    django项目使用uwsgi方式启动
    django+wsgi+nginx 环境ubuntu
    Django + Uwsgi + Nginx 的生产环境部署实战
    认识Nginx并部署Django项目
    Django、Nginx、uWSGI详解及配置示例

  • 相关阅读:
    量子信息基础知识与实践指南
    设计模式之MVC模式
    学习ASP.NET Core Blazor编程系列十四——修改
    前端工作总结247-uni-拼接解决下拉刷新问题
    .NET Emit 入门教程:第五部分:动态生成方法(MethodBuilder 与 DynamicMethod)
    HOWTO:在 Tomcat 中禁用 HTTP 方法
    若依分割拼接图片地址
    C++空间配置器
    盲盒经济为什么能火
    如何将 Helm Chart 推送至 Harbor ?
  • 原文地址:https://blog.csdn.net/cooper_wx/article/details/137948945