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'
python manage.py collectstatic  # 按照 STATIC_ROOT 收集静态文件
项目下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<path>.*)', serve, {'document_root': settings.STATIC_ROOT}, name='static')
    # 定义媒体资源的路由信息
    re_path('media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}, name='media'),
]

1、安装uwsgi 和配置uwsgi

安装uWSGI
pip3 install uwsgi
测试uWSGI是否安装成功
在终端中输入以下命令查看uwsgi的版本号,如果输出正常,说明uswgi已安装成功
$ uwsgi --version
2.0.15
如果想要运行项目来测试

# uwsgi --http :8000 --chdir 项目路径 -w 项目.wsgi 静态文件地址--static-map=/static=static

uwsgi --http :8000 --chdir /home/teacher/ -w teacher.wsgi --static-map=/static=static

推荐配置文件启用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

使用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

2、安装 nginx和配置

yum install nginx -y  安装

systemctl start nginx   启动
systemctl stop nginx   停止
systemctl status nginx  查看状态
systemctl restart nginx  重启
systemctl enable nginx  开机自启动

niginx 配置

安装nginx后,默认的配置文件在
/etc/nginx/nginx.conf
修改nginx.conf

基本配置
# 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 {
#        }
#    }

}


完整配置 (待验证)
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";
        }
    }
}

3、运行

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

在这里插入图片描述

脚本运行

启动脚本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

停止脚本 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


参考资料

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

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Linux系统上部署Django + nginx + uWSGI的步骤如下: 1. 安装必要的软件 在Linux系统上安装必要的软件包,包括Python、pip、nginxuWSGI等。 2. 创建Django项目 使用Django创建一个新项目使用现有的Django项目。 3. 配置uWSGIDjango项目的根目录下创建一个uwsgi.ini文件,用于配置uWSGI。示例配置如下: ``` [uwsgi] # 指定运行模式为WSGI http = :8000 # 指定Django应用的wsgi模块 wsgi-file = myproject.wsgi # 指定进程数 processes = 4 # 指定线程数 threads = 2 # 指定静态文件路径 static-map = /static=/path/to/static # 指定日志路径 logto = /path/to/logfile ``` 其中,http参数指定了监听的端口号,wsgi-file参数指定了Django应用的wsgi模块,processes参数指定了进程数,threads参数指定了线程数,static-map参数指定了静态文件的路径,logto参数指定了日志文件的路径。 4. 配置nginxnginx的配置文件中添加以下内容: ``` server { listen 80; server_name example.com; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { uwsgi_pass 127.0.0.1:8000; include uwsgi_params; } location /static { alias /path/to/static; } } ``` 其中,server_name指定了域名,access_log和error_log指定了日志文件的路径,uwsgi_pass指定了uWSGI的地址和端口号,include指定了uWSGI的参数。 5. 启动uWSGI服务 使用以下命令启动uWSGI服务: ``` uwsgi --ini uwsgi.ini ``` 6. 启动nginx服务 使用以下命令启动nginx服务: ``` sudo service nginx start ``` 这样就完成了Django + nginx + uWSGI部署。可以通过访问该网站的域名来验证是否部署成功。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值