温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python3 中怎么利用Nginx 部署一个Django 项目

发布时间:2021-06-22 16:33:46 来源:亿速云 阅读:279 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关Python3 中怎么利用Nginx 部署一个Django 项目,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、工作原理
Django 的部署可以有很多方式,采用 nginx + uwsgi 的方式是其中比较常见的一种方式。

在这种方式中,我们的通常做法是,将 nginx 作为服务器最前端,它将接收 web 的所有请求,统一管理请求。nginx 把所有静态请求自己来处理(这是 nginx 的强项)。然后,nginx 将所有非静态请求通过 uwsgi 传递给 Django,由 Django 来进行处理,从而完成一次 web 请求。

可见,uwsgi 的作用就类似一个桥接器,起到桥梁的作用。

Linux 的强项是用来做服务器,所以,下面的整个部署过程我们选择在 Ubuntu 16.04 下完成。

技术扩展:

WSGI 是 Web Server Gateway Interface 的缩写。以层的角度来看,WSGI 所在层的位置低于 CGI。但与 CGI 不同的是 WSGI 具有很强的伸缩性且能运行于多线程或多进程的环境下,这是因为 WSGI 只是一份标准并没有定义如何去实现。实际上 WSGI 并非 CGI,因为其位于 web 应用程序与 web 服务器之间,而 web 服务器可以是 CGI。可以理解为是 Python 内置的一个测试 web 服务器。

uWSGI 是一个Web服务器,它实现了 WSGI 协议、uwsgi、http 等协议。Nginx 中HttpUwsgiModule 的作用是与 uWSGI 服务器进行交换。WSGI 是一种 Web 服务器网关接口。比如把 HTTP 协议转化成 WSGI 协议,让 Python 可以直接使用。

二、项目环境
操作系统: Ubuntu 16.04

编程语言: Python 3.5.2

Web 框架: Django 2.0.3

Web 服务器: uWSGI 2.0.17

Web 服务器: Nginx 1.10.3

具体的安装这里不做详述,Ubuntu 使用 apt-get 安装特别方便。

sudo apt-get install python3
sudo apt-get install python3-pip
sudo apt-get install nginx
1
2
3
Nginx 安装成功在浏览器中输入 127.0.0.1,出现 “Welcome to nginx!”表示安装成功。

三、uWSGI 安装配置
安装
sudo pip3 install uwsgi
1
测试
创建 test.py 文件

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b'Hello World']
1
2
3
4
5
6
通过 uWSGI 运行该文件

uwsgi --http :8000 --wsgi-file test.py
1
在浏览器中输入 127.0.0.1:8000,出现 “Hello World”表示安装成功。

四、Django 与 uWSGI 之间的通信
安装 Django
sudo pip3 install Django==2.0.3
1
创建 Django 项目
django-admin startproject myweb
1
我的 Django 项目位置为:/home/setup/myweb

uwsgi --http :8000 --chdir /home/setup/myweb --wsgi-file myweb/wsgi.py --master --processes 4 --threads 2 --stats 127.0.0.1:8001
1
常用选项
http: 协议类型和端口号

processes: 开启的进程数量

workers: 开启的进程数量,等同于 processes

chdir: 指定运行目录

wsgi-file: 载入 wsgi-file

stats: 在指定的地址上,开启状态服务

threads: 运行线程。由于 GIL 的存在,我觉得这个真心没啥用。

master: 允许主进程存在

daemonize: 使进程在后台运行,并将日志打到指定的日志文件或者 udp 服务器(daemonize uWSGI)。实际上最常用的,还是把运行记录输出到一个本地文件上。

pidfile: 指定pid文件的位置,记录主进程的pid号。

vacuum: 当服务器退出的时候自动清理环境,删除 unix socket 文件和 pid 文件

五、Nginx、uWSGI、Django 之间的通信
接下来,我们要将三者结合起来

1. 配置 Django 和 uWSGI
先在 Django 项目根目录下新建一个 uWSGI 的配置文件 uwsgi.ini

cd myweb
touch uwsgi.ini 
1
2
此时 Django 项目的目录文件结构如下:

myweb/
├── manage.py
├── myweb
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-35.pyc
│   │   └── settings.cpython-35.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── uwsgi.ini
1
2
3
4
5
6
7
8
9
10
11
在我们通过 Django 创建 myweb 项目时,在子目录 myweb 下已经帮我们生成的 wsgi.py文件。所以,我们只需要再创建 uwsgi.ini 配置文件即可。

uwsgi 支持多种类型的配置文件,如 xml、ini 等。此处,使用 ini 类型的配置。

接下来打开刚刚创建好的配置文件 uwsgi.ini 添加如下配置:

[uwsgi]

socket = :8888
chdir           = /home/setup/myweb
module          = myweb.wsgi
master          = true
processes       = 4
vacuum          = true
1
2
3
4
5
6
7
8
这个配置,其实就相当于在上一小节中通过 wsgi 命令,后面跟一堆参数的方式,给文件化了。

socket: 指定项目执行的端口号。

chdir: 指定项目的目录。

module: module = hello.wsgi 可以这么来理解。对于 uwsgi.ini 文件而言,与它同级目录有一个 myweb 目录,这个目录下有一个 wsgi.py 文件。

其它几个参数,可以参考上一小节中参数的介绍。

接下来,通过 uwsgi 命令读取 uwsgi.ini 文件启动项目

uwsgi --ini uwsgi.ini
1
运行结果:

setup@labideas-data:~/myweb$ uwsgi --ini uwsgi.ini
[uWSGI] getting INI configuration from uwsgi.ini
*** Starting uWSGI 2.0.17 (64bit) on [Tue Mar 20 11:11:30 2018] ***
compiled with version: 5.4.0 20160609 on 19 March 2018 09:13:12
os: Linux-4.4.0-105-generic #128-Ubuntu SMP Thu Dec 14 12:42:11 UTC 2017
nodename: labideas-data
machine: x86_64
clock source: unix
detected number of CPU cores: 4
current working directory: /home/setup/hello
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
chdir() to /home/setup/hello
your processes number limit is 64049
your memory page size is 4096 bytes
detected max file descriptor number: 65535
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address :8888 fd 3
Python version: 3.5.2 (default, Nov 23 2017, 16:37:01)  [GCC 5.4.0 20160609]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x1f73aa0
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 364520 bytes (355 KB) for 4 cores
*** Operational MODE: preforking ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x1f73aa0 pid: 7097 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 7097)
spawned uWSGI worker 1 (pid: 7099, cores: 1)
spawned uWSGI worker 2 (pid: 7100, cores: 1)
spawned uWSGI worker 3 (pid: 7101, cores: 1)
spawned uWSGI worker 4 (pid: 7102, cores: 1)
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
注意查看uwsgi的启动信息,如果有错,就要检查配置文件的参数是否设置有误。

2. 配置 Nginx
Nginx 默认的配置文件都在 /etc/nginx 目录下

setup@labideas-data:/etc/nginx$ ll
total 64
drwxr-xr-x  6 root root 4096 Mar 20 09:37 ./
drwxr-xr-x 95 root root 4096 Mar 19 19:56 ../
drwxr-xr-x  2 root root 4096 Mar 19 20:13 conf.d/
-rw-r--r--  1 root root 1077 Feb 12  2017 fastcgi.conf
-rw-r--r--  1 root root 1007 Feb 12  2017 fastcgi_params
-rw-r--r--  1 root root 2837 Feb 12  2017 koi-utf
-rw-r--r--  1 root root 2223 Feb 12  2017 koi-win
-rw-r--r--  1 root root 3957 Feb 12  2017 mime.types
-rw-r--r--  1 root root 1919 Mar 20 09:33 nginx.conf
-rw-r--r--  1 root root  180 Feb 12  2017 proxy_params
-rw-r--r--  1 root root  636 Feb 12  2017 scgi_params
drwxr-xr-x  2 root root 4096 Mar 20 10:00 sites-available/
drwxr-xr-x  2 root root 4096 Mar 19 14:59 sites-enabled/
drwxr-xr-x  2 root root 4096 Mar 19 14:59 snippets/
-rw-r--r--  1 root root  664 Feb 12  2017 uwsgi_params
-rw-r--r--  1 root root 3071 Feb 12  2017 win-utf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
我们需要进入 /etc/nginx/sites-available 目录下进行配置 default 文件(有些 Linux 发行版的配置文件是在 /etc/nginx/nginx.conf 下,还有一些在其他地方,这里我们以 Ubuntu 16.04 为准)。

将原有配置文件进行备份,并打开 nginx 配置文件

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.bak
sudo vi /etc/nginx/sites-available/default
1
2
将默认的 80 端口号改成其它端口号,如 8080。因为默认的 80 端口号很容易被其它应用程序占用,而且我们配置我们自己的 Django 项目也需要用到默认端口。

# Django 2.0 项目部署
server {

    listen          80; 
    server_name     data.labideas.cn 
    charset         UTF-8;
    access_log      /var/log/nginx/myweb_access.log;
    error_log       /var/log/nginx/myweb_error.log;

    client_max_body_size 75M;

    location / { 

        include uwsgi_params;
        uwsgi_pass 127.0.0.1:8888;
        uwsgi_read_timeout 2;
    }   

    location /static {

        expires 30d;
        autoindex on; 
        add_header Cache-Control private;
        alias /home/setup/myweb/static/;
    }   
}
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
listen: 指定的是 nginx 代理 uwsgi 对外的端口号。

server_name: 网上大多资料都是设置的一个网址(例,www.baidu.com,如果指定的是 localhost 或 127.0.0.1 则只能在本机访问。

那么 nginx 到底是如何 uwsgi 产生关联的呢?现在看来大概最主要的就是这两行配置。

include uwsgi_params;
uwsgi_pass 127.0.0.1:8888;
1
2
include 必须指定为 uwsgi_params。而 uwsgi_pass 指的是本机 IP 和端口号,并且要与 myweb_uwsgi.ini 配置文件中的 IP 和端口号必须保持一致。

现在重新启动 nginx

sudo /etc/init.d/nginx restart
1
然后浏览器访问 127.0.0.1

Invalid HTTP_HOST header: 'data.labideas.cn'. You may need to add 'data.labideas.cn' to ALLOWED_HOSTS.
[pid: 7924|app: 0|req: 1/1] 114.249.204.30 () {40 vars in 658 bytes} [Tue Mar 20 06:16:28 2018] GET / => generated 54903 bytes in 41 msecs (HTTP/1.1 400) 1 headers in 53 bytes (1 switches on core 0)
1
2
在 uWSGI 后台就可以看到有信息输出。通过 IP 和端口号的指向,请求应该是先到 nginx 的,如果你在页面上执行一些请求,就会看到,这些请求最终会转到 uwsgi 来处理。

最后我们将 uWSGI 配置为开机自启

打开 sudo vi /etc/rc.local 将

uwsgi --ini /home/setup/myweb/uwsgi.ini &
1
添加到文件中

注意要添加到 exit 0 之前,& 表示该服务是在后台执行。

六、遇到的问题
在配置过程中,总会遇到各种各样的问题,这里我将最常用的几项问题罗列出来,希望能帮到你。

1. Django 启动报错
setup@labideas-data:~/myweb$ python3 manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

March 20, 2018 - 06:28:52
Django version 2.0.3, using settings 'myweb.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
1
2
3
4
5
6
7
8
9
10
11
12
创建一个新项目,利用 Django 本身的测试服务器启动,会出现上述的错误。这是因为你的项目中有些默认数据并没有迁移到数据库中。

解决办法:

将数据迁移到数据库中

python3 manage.py migrate
1
2. uwsgi 启动报错
在启动 uwsgi 的时候,在启动信息中如果有下面的错误提示:

!!! no internal routing support, rebuild with pcre support !!!
1
是依赖有问题

解决办法:

卸载 uwsgi,注意此时卸载,pip 会有缓存留在系统里

pip uninstall uwsgi
1
安装 pcre 依赖库

centos 安装

sudo yum install pcre pcre-devel pcre-static
1
ubuntu 安装

sudo apt-get install libpcre3 libpcre3-dev
1
重新安装 uwsgi,不走 pip 缓存

pip install uwsgi -I --no-cache-dir
1
再次启动 uwsgi,已经没有 !!! no internal routing support, rebuild with pcre support !!! 的报错了。

3. 端口报错
有时候进过多次配置,启动 Django 和 uWSGI 可能会出现如下报错

Error: That port is already in use
1
这是端口号已被占用,是 servr 已经在运行了,也有可能在后台运行或者是你停掉可 Django 但是,进程资源和端口号并没有释放掉。

解决办法:

找到该进程 kill 掉即可

sudo ps aux | grep uwsgi
sudo kill -9 PID
1
2
或者最简单的解决方法就是直接杀掉

sudo fuser -k 8000/tcp
1
这样和端口 8000 相关的进程就都死掉了

4. 公网端口安全组屏蔽
还有一些情况,感觉明明所有东西都配置好了,还检查了好多遍。本地没有一丁点问题,但是一上线就日了狗了,总是报“服务器未响应”等错误,或者 localhost 能访问,但是就是使用域名或外网访问不了,气的都想砸电脑…这又是怎么一回事呢?

项目在正式的环境中上线,一定是在公网上的,有时候我们会选择云服务器,这里以阿里云服务器为例,我们需要为其开放对应的端口号。

聪明的同学可能已经有所觉察,为什么上图中并没有 uwsgi.ini 文件中 8888 的端口号呢?

这是因为,阿里云的安全组规则端口是对外屏蔽的,我们 Nginx 和 uWSGI 之间通信的 socket 端口号 8888 是在内网环境中,所以不受影响。

5. 正式上线模式
因为我们在实际开发的时候,需要用到 DEBUG 模式,但是在正式上线的时候我们需要关闭 DEBUG 模式。

打开 Django 项目中的 settings.py 配置文件

DEBUG = True
1
修改为

DEBUG = False
1

ALLOWED_HOSTS = []
1
修改为

ALLOWED_HOSTS = ['data.labideas.cn']
1
或者

ALLOWED_HOSTS = ['*']
1
建议不使用通配符 *,添加具体的域名即可!

6. Admin 管理界面样式表丢失
曾几何时,Admin 是检验 Django 是否成功安装的标准。但是在正式环境中,经常会遇到样式表丢失的问题。为什么会这样呢?

这是因为 Nginx 在正式环境中,找不到 Django 项目中的静态文件。

解决办法:

① 在 Django 项目中新建一个 static 目录,用于放置一些静态文件

② 打开 Django 项目中的 settings.py 配置文件

添加一行

STATIC_ROOT = '/home/setup/myweb/static/'
1
将 STATIC_ROOT 指向存放静态文件的 static 目录

③ 从 Django 资源包中复制必须的静态文件到 STATIC_ROOT 指向的 static 目录中,这其中包括 admin 界面所必须的样式表(style)、图片(image)及脚本(js)等。

python3 manage.py collectstatic
1
需要注意的是,假如不做第 ① 步的话,直接运行这个命令会导致错误发生。

④ 修改 Nginx 配置文件

location /static {

    expires 30d;
    autoindex on; 
    add_header Cache-Control private;
    alias /home/setup/html/data/static/;
}

将 alias 也指向存放静态文件的 static 目录,需要和 Django 项目中的 settings.py 配置文件中的 STATIC_ROOT 指向目录保持一致。

⑤ 重启 uWSGI 和 Nginx

# 杀掉 uwsgi.ini 进程
ps aux | grep uwsgi | grep -v grep | awk '{print $2}' | xargs kill -9
uwsgi --ini /home/setup/html/data/uwsgi.ini &

sudo /etc/init.d/nginx restart

关于Python3 中怎么利用Nginx 部署一个Django 项目就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI