使用nginx和uwsgi将django项目部署到云服务器

一. 简介

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

nginx (pronounced engine-x) is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server.

A Web Server Gateway Interface - WSGI - does this job. WSGI is a Python standard.

二. 组件概览

the web client <-> the web server <-> the socket <-> uwsgi <-> Django

nginx充当the web server,响应处理静态资源的请求,并将动态资源的请求通过socket以uwsgi协议转发给uWSG处理,uWSG则是运行django项目的web服务。

三. 具体步骤

逐步搭建,方便排查问题。以下步骤若未特殊声明,则均在云服务器上执行。

1. virtualenv

方法一:
安装virtualenv

sudo apt-get install virtualenv

创建和激活virtualenv

virtualenv env --no-site-packages --python=python3
source env/bin/activate

--no-site-packages 表示不使用系统已经安装的第三方库
--python指定项目用到的python版本

方法二:
使用python3内置venv

$ python3 -m venv envpy3
2. 测试uwsgi

将uwsgi安装到virtualenv中。激活virtualenv再执行

pip install uwsgi

新建文件test.py并写入以下内容

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

运行uwsgi

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

访问127.0.0.1:8000查看是否成功,若成功说明以下组件连接成功

the web client <-> uWSGI <-> Python
3. 测试django项目

在本机django的项目根目录执行以下命令,生成项目依赖清单requirements.txt

pip freeze > requirements.txt

用scp命令将django项目传到云服务器

 scp [option] <localfile> <username>@<host>:<remote-file-location>
示例:
scp -r /home/user/hello_django user@x.x.x.x:/home/user/

激活virtualenv,切换到项目根目录下安装依赖

pip install -r requirements.txt

运行django

python manage.py runserver 0.0.0.0:8000

如果运行成功,再测试使用uwsgi运行django

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

--module 指定django模块
如果成功,说明以下组件连接成功

the web client <-> uWSGI <-> Django
4. 测试nginx

安装

sudo apt-get install nginx

启动

sudo systemctl start nginx

nginx默认监听80端口,所以可以访问127.0.0.1:80测试是否成功。
nginx安装之后,会默认创建www-data用户和组,并以www-data身份运行nginx(可以在/etc/nginx/nginx.conf首行查看或修改)。为了避免文件访问权限问题,修改django项目的用户组

sudo chown -R :www-data hello_django
5. 部署静态资源

在django项目的settings.py文件添加

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

然后执行

python manage.py collectstatic

即可将项目的静态资源统一收集到项目根目录下的static文件夹中。

在/etc/nginx/sites-available/目录下,新建hello_django.conf并写入以下内容,将static路径替换成上面的项目的static目录路径

# mysite_nginx.conf

# the upstream component nginx needs to connect to
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
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste
   
    # 开启gzip
    gzip on;

    # 启用gzip压缩的最小文件,小于设置值的文件将不会压缩
    gzip_min_length 1k;

    # gzip 压缩级别,1-10,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
    gzip_comp_level 2;

    # 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;

    # 是否在http header中添加Vary: Accept-Encoding,建议开启
    gzip_vary on;

    # 禁用IE 6 gzip
    gzip_disable "MSIE [1-6]\.";

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

    location /static {
        alias /path/to/your/mysite/static; # your Django project's static files - amend as required
        # enable cache 
        expires 30d; 
    }

    # 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
    }
}

并创建软链接到/etc/nignx/sites-enabled目录

sudo ln -s /etc/nginx/sites-available/hello_django.conf /etc/nginx/sites-enabled/

重加载nginx

nginx -s reload

然后访问127.0.0.1:8000/static/xxx/xxx.png,若成功说明静态资源部署成功。
若访问失败可查看nginx错误日志(/var/log/nginx/error.log),Permission denied问题请将static目录加入到www-data用户组。

6. 连接nginx和uwsgi

以--socket方式运行django项目,并将端口改成nginx中配置的8001端口

uwsgi --socket :8001 --module hello_django.wsgi 

然后访问127.0.0.1:8000查看测试nginx的动态转发是否成功。
若成功,则所有组件的连接都成功了

the web client <-> the web server <-> the socket <-> uWSGI <-> Python
7. 使用Unix sockets替换uwsgi的端口

nignx和uwsgi间通过socket端口连接虽然简单,但是不是最佳方式,应改用Unix sockets。
修改hello_django.conf

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)

指定使用Unix sockets时创建的sock文件,如

server unix:///home/www-data/hello_django/hello_django.sock; # for a file socket

然后改以unit socket方式运行django

uwsgi --socket /home/www-data/hello_django/hello_django.sock --module hello_django.wsgi --chmod-socket=666

--chmod-socket是为了避免hello_django.sock文件的权限问题
然后访问查看是否成功。

8. 以.ini文件方式运行uwsgi

创建文件 hello_django_uwsgi.ini

[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /path/to/your/project
# Django's wsgi file
module          = project.wsgi
# the virtualenv (full path)
home            = /path/to/virtualenv

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10
# the socket (use the full path to be safe
socket          = /path/to/your/project/mysite.sock
# ... with appropriate permissions - may be needed
chmod-socket    = 666
# clear environment on exit
vacuum          = true

然后指定文件启动uwsgi

uwsgi --ini hello_django_uwsgi.ini # the --ini option is used to specify a file
9. 将uwsgi配置成service并设置开机自启

退出virtualenv

deactivate

将uwsgi安装到系统环境

sudo pip3 install uwsgi

然后用系统环境的uwsgi测试

uwsgi --ini mysite_uwsgi.ini # the --ini option is used to specify a file

在/etc/systemd/system目录,新建文件hello_django.service

[Unit]
Description=hello django uwsgi web service
After=syslog.target

[Service]
Type=simple
ExecStart= /usr/local/bin/uwsgi --ini /path/to/your/hello_django.ini
Restart=always
StandardError=syslog

[Install]
WantedBy=multi-user.target

配置完成后,reload一下systemd,即成功添加了hello_django的service

$ sudo systemctl daemon-reload

启动

systemclt start hello_django

设置开机自启

systemctl enable hello_django

systemd还可以监控服务进程,代替supervisor第三方库。

10. 其他

以Emperor模式启动uwsgi,该模式下,会监视uwsgi的配置文件,当配置文件被修改后,会自动重启uwsgi下对应的web服务。

# create a directory for the vassals
sudo mkdir /etc/uwsgi
sudo mkdir /etc/uwsgi/vassals
# symlink from the default config directory to your config file
sudo ln -s /path/to/your/mysite/mysite_uwsgi.ini /etc/uwsgi/vassals/
# run the emperor
uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

启动

sudo uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data

在hello_django.service的配置文件中修改启动的shell命令

/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals --uid www-data --gid www-data --daemonize /var/log/uwsgi-emperor.log

参考文章
https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容