通过uwsgi和nginx部署django项目

时间:2021-07-13 21:05:15

django项目在服务器上的部署

在linux服务器上采用uwsgi + nginx的方式部署运行。

uwsgi负责django项目的python动态解析;nginx负责静态文件转发,以及uwsgi_pass到uwsgi。

此外,在运行nginx之前,需要先收集Django项目的静态文件到static目录。

首先,需要在settings.py文件中添加:

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

并注释掉之前的:

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

注意:上面两条配置不能并存。如果是本地开发的话,用STATICFILES_DIRS这条配置

然后,运行collectstatic命令:

python manage.py collectstatic

相关的uwsgi配置: uwsgi.ini

[uwsgi]
chdir = /opt/mysite
module = mysite.wsgi
master = true
processes = 4
socket = 127.0.0.1:8001
vacuum = true

uwsgi运行命令

类似如下:

nohup uwsgi uwsgi.ini --plugin python >> uwsgi.log &

相关nginx配置

upstream django {
# server unix:///path/to/your/mysite/mysite.sock; # for a file socket
server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
# the port your site will be served on
listen 8000;
# the domain name it will serve for
#server_name .example.com; # substitute your machine's IP address or FQDN
server_name localhost;
charset utf-8;

# max upload size
client_max_body_size 75M; # adjust to taste

# Django media
#location /media {
# alias /path/to/your/mysite/media; # your Django project's media files - amend as required
#}

location /static {
alias /opt/xloader/static; # your Django project's static files - amend as required
}

# Finally, send all non-media requests to the Django server.
location / {
uwsgi_pass django;
include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
}
}