Django项目使用uwsgi+nginx部署上线
- 前言
- [settings 配置](#settings 配置)
- [安装uwsgi 和配置uwsgi](#安装uwsgi 和配置uwsgi)
-
- 推荐配置文件启用wsgi
- [安装 nginx和配置](#安装 nginx和配置)
-
- [niginx 配置](#niginx 配置)
- 运行
- 参考资料
前言
代码已经开发完成,正式部署上线
settings 配置
python
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
python manage.py collectstatic # 按照 STATIC_ROOT 收集静态文件
python
项目下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'),
]
安装uwsgi 和配置uwsgi
python
安装uWSGI
pip3 install uwsgi
测试uWSGI是否安装成功
在终端中输入以下命令查看uwsgi的版本号,如果输出正常,说明uswgi已安装成功
$ uwsgi --version
2.0.15
python
如果想要运行项目来测试
# 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的配置(不推荐)
python
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的配置
python
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
安装 nginx和配置
python
yum install nginx -y 安装
systemctl start nginx 启动
systemctl stop nginx 停止
systemctl status nginx 查看状态
systemctl restart nginx 重启
systemctl enable nginx 开机自启动
niginx 配置
python
安装nginx后,默认的配置文件在
/etc/nginx/nginx.conf
修改nginx.conf
python
基本配置
# 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 {
# }
# }
}
python
完整配置 (待验证)
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";
}
}
}
运行
python
systemctl start nginx
进入到虚拟环境后(按需)
找到uwsgi.ini的配置文件
uwsgi --ini uwsgi.ini & 加上 & 表示后台运行
参考资料
django项目使用uwsgi方式启动
django+wsgi+nginx 环境ubuntu
Django + Uwsgi + Nginx 的生产环境部署实战
认识Nginx并部署Django项目
Django、Nginx、uWSGI详解及配置示例