简单使用 uwsgi + nginx 在本地 Ubuntu 成功部署 django 项目

导读:本篇文章讲解 简单使用 uwsgi + nginx 在本地 Ubuntu 成功部署 django 项目,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一,查看环境与版本

1,查看系统环境:

$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 21.10
Release:	21.10
Codename:	impish

2,查看python版本:

$ python3 -V
Python 3.9.7

3,查看django版本:

$ python3
Python 3.9.7 (default, Sep 10 2021, 14:59:43) 
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.get_version()  # 获取当前djiango版本号
'3.2.1'

4,查看 pip3 版本:

$ pip3 -V
pip 20.3.4 from /usr/lib/python3/dist-packages/pip (python 3.9)

5,看一下项目目录:

dfl@WEB:~/deployment/testdeployment$ tree
.
├── blog
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── static
│   │   └── css
│   │       └── index.css
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── README.md
└── venv

二,安装 uWSGI

1,安装 uWSGI

# 安装
$ sudo pip3 install uwsgi
Collecting uwsgi
  Downloading uwsgi-2.0.20.tar.gz (804 kB)
     |████████████████████████████████| 804 kB 475 kB/s 
Building wheels for collected packages: uwsgi
  Building wheel for uwsgi (setup.py) ... done
  Created wheel for uwsgi: filename=uWSGI-2.0.20-cp39-cp39-linux_x86_64.whl size=520821 sha256=414b6738e97ac0b833c18d7a8f562b9486548249f57f11cf4d7dfc35963a986f
  Stored in directory: /root/.cache/pip/wheels/09/ac/7b/80681f729cf8c820803228c8752d49581afd6a446bc58b172c
Successfully built uwsgi
Installing collected packages: uwsgi
Successfully installed uwsgi-2.0.20

2 ,启动 uWSGI

# 启动
$ uwsgi
*** Starting uWSGI 2.0.20 (64bit) on [Sat Feb 19 18:45:33 2022] ***
compiled with version: 11.2.0 on 19 February 2022 10:44:59
os: Linux-5.13.0-28-generic #31-Ubuntu SMP Thu Jan 13 17:41:06 UTC 2022
nodename: WEB
machine: x86_64
clock source: unix
detected number of CPU cores: 8
current working directory: /home/dfl
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 44766
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
The -s/--socket option is missing and stdin is not a socket.

报错:启动 uwsgi 出现 !!! no internal routing support, rebuild with pcre> support> !!!

完全成功:

$ uwsgi
*** Starting uWSGI 2.0.20 (64bit) on [Sat Feb 19 19:06:09 2022] ***
compiled with version: 11.2.0 on 19 February 2022 11:05:58
os: Linux-5.13.0-28-generic #31-Ubuntu SMP Thu Jan 13 17:41:06 UTC 2022
nodename: WEB
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /home/dfl
detected binary path: /usr/local/bin/uwsgi
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 44766
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
The -s/--socket option is missing and stdin is not a socket.

3,测试 uWSGI:
先查询 IP 地址:
在这里插入图片描述
然后在项目根目录创建一个测试文件 test-uwsgi.py :

# -*-coding:utf-8-*-

# 测试uwsgi
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b'<h1>Hello, web!</h1>']

启动 uWSGI:

$ uwsgi --http :9001 --wsgi-file blog/utils/test-uwsgi.py --callable application
  • 9001是一个之前未被占用的端口。

问题:

启动 uwsgi 报错:bind(): Address already in use [core/socket.c line 769]

打开浏览器,访问http://192.168.1.14:9001/,如果出现 test-uwsgi 文件返回的内容,则表示 uwsgi 安装成功:
在这里插入图片描述

三,安装Nginx

1,安装:

$ sudo apt-get install nginx

2,测试:
先启动 nginx 服务:

$ sudo service nginx start
$ systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2022-02-19 20:20:57 CST; 23min ago
       Docs: man:nginx(8)
    Process: 1055645 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 1055646 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 1055647 (nginx)
      Tasks: 9 (limit: 13429)
     Memory: 7.7M
        CPU: 32ms
......

问题:

启动nginx服务报错:nginx.service: control process exited, code=exited status=1?
Nginx服务重启失败:Job for nginx.service failed because

最后打开浏览器,访问http://192.168.1.14,显示欢迎页面:

  • 一般会出现:
    在这里插入图片描述
  • 但有时候会出现:
    在这里插入图片描述

具体依赖于:

dfl@WEB:/var/www/html$ ls -l
总用量 16
-rw-r--r-- 1 root root 10918  111 22:49 index.html
-rw-r--r-- 1 root root   612  219 19:57 index.nginx-debian.html

四,项目准备

1,修改项目配置

(1)配置静态文件收集路径

先添加配置:

STATIC_URL = '/static/'

# 在以下路径中搜索静态文件
STATICFILES_DIRS = [
    BASE_DIR / 'blog/static/',
]

# 将所有静态文件存储在一个文件夹中
STATIC_ROOT = BASE_DIR / 'static/'

执行静态文件收集命令:

$ python3 manage.py collectstatic

You have requested to collect static files at the destination
location as specified in your settings:

    /home/dfl/deployment/testdeployment/static

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

0 static files copied to '/home/dfl/deployment/testdeployment/static', 128 unmodified.

django 会将所有能搜索到的静态文件筹集到项目根目录的 static 目录中。

问题:

PermissionError: [Errno 13] Permission denied: ‘/static’

(2)关闭调试

DEBUG = False

(3)开启访问限制

ALLOWED_HOSTS = [
    '127.0.0.1',
    'localhost',
    '192.168.1.14',
    '*'
]

(4)删除数据迁移文件

删除数据迁移目录中以数字开头的所有数据迁移文件。

(5)收集项目依赖

$ pip3 freeze>requirements.txt

2,配置Nginx

1,复制 /etc/nginx/nginx_params 文件到项目根目录:

$ sudo cp /etc/nginx/nginx_params .

2,创建 nginx 配置文件 testdeployment_nginx.conf :

$ cat testdeployment_nginx.conf

upstream django {
	server 127.0.0.1:9001;	# 记住这里的端口号,后面会用于与 uwsgi 的 socket 进行通信
}
server {
	listen 8000;				# 对外开放的端口号
	server_name 192.168.1.17;	# 之前查到的本地 IP 地址
	charset utf-8;
	location / {				# 主页配置
		uwsgi_pass django;
		include /home/dfl/deployment/testdeployment/uwsgi_params;
	}
	location /static {			# 静态文件配置,必须与前面 STATIC_ROOT 的路径一致
        alias /home/dfl/deployment/testdeployment/static;
    }
}

查看是否有语法问题:

dfl@WEB:~$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

3,创建一个软链接,将这里的 nginx 配置文件连接到默认的配置文件

$ sudo ln -s /home/dfl//deployment/testdeployment/testdeployment_nginx.conf /etc/nginx/sites-enabled/

$ cd /etc/nginx/sites-enabled/
/etc/nginx/sites-enabled$ ls -l
总用量 0
lrwxrwxrwx 1 root root 34  219 19:57 default -> /etc/nginx/sites-available/default
lrwxrwxrwx 1 root root 50  220 13:35 testdeployment_nginx.conf -> /home/dfl//deployment/testdeployment/testdeployment_nginx.conf

问题:

如果因为 Too many levels of symbolic links 问题导致失败,请使用绝对路径!

4,重启 nginx :

$ sudo service nginx restart

问题:

端口号占用问题:nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in
use)
1,看看端口占用情况:sudo lsof -i:端口号

2,查看具体服务的进程信息:ps -ef | grep 服务名

3,服务控制:查看服务状态——systemctl status nginx.service, 启动服务——service nginx start,停止服务——service nginx stop,重启服务——service nginx start

3,配置 uwsgi :

1,同样在项目根目录创建配置文件 testdeployment_uwsgi.ini :

[uwsgi]

chdir = /home/dfl/deployment/testdeployment

module = testdeployment.wsgi

master = true

processes = 2

socket = 127.0.0.1:9001		# 必须与 nginx 配置文件保持一致!

chmod-socket = 662

vacuum = true

2,初始化启动 uwsgi:

$ uwsgi --ini typeidea_uwsgi.ini

问题:

uwsgi 启动次数过多:probably another instance of uWSGI is running on the same address (127.0.0.1:9001).
杀掉端口上的 tcp 进程sudo fuser -k 9001/tcp

如果是普通静态文件显示 net::ERR_ABORTED 403 (Forbidden) 或者直接 404,多半是因为 settings 中各项静态文件相关配置或者 nginx 中静态文件相关配置出现问题。
如果浏览器 F12 中能显示接收到静态文件但状态码是 304,则需要将 html 文件的 改成 <!DOCTYPE>。
如果部署后 admin 样式丢失显示404,需要将 /etc/nginx/nginx.conf 顶部将 user 改为 root。

启动 nginx 和 uwsgi,看到普通页面和 admin 都能正常显示出静态文件的效果来,就表示部署成功了:
在这里插入图片描述
在这里插入图片描述
成功部署后,同一局域网下可直接访问:
在这里插入图片描述

最后再来看看项目结构:

dfl@WEB:~/deployment/testdeployment$ tree
.
├── blog
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── static
│   │   └── css
│   │       └── index.css
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── README.md
├── requirements.txt
├── static
│   ├── admin
│   │   ├── css
│   │   ├── fonts
│   │   └── js
│   └── css
├── templates
│   └── index.html
├── testdeployment
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── testdeployment_nginx.conf
├── testdeployment_uwsgi.ini
├── test-uwsgi.py
├── uwsgi_params
└── venv

查看 nginx 的状态:

dfl@WEB:~$ systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-04-10 20:16:51 CST; 1h 13min ago
       Docs: man:nginx(8)
    Process: 560572 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, st>
    Process: 560573 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SU>
   Main PID: 560574 (nginx)
      Tasks: 9 (limit: 16530)
     Memory: 7.9M
        CPU: 98ms
     CGroup: /system.slice/nginx.service
             ├─560574 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             ├─560777 nginx: worker process
             ├─560778 nginx: worker process
             ├─560779 nginx: worker process
             ├─560780 nginx: worker process
             ├─560781 nginx: worker process
             ├─560782 nginx: worker process
             ├─560783 nginx: worker process
             └─560784 nginx: worker process

410 20:16:51 WEB systemd[1]: Starting A high performance web server and a reverse proxy server...
410 20:16:51 WEB systemd[1]: Started A high performance web server and a reverse proxy server.

uwsgi 启动后的状态:

dfl@WEB:~/deployment/testdeployment$ uwsgi --ini testdeployment_uwsgi.ini
[uWSGI] getting INI configuration from testdeployment_uwsgi.ini
*** Starting uWSGI 2.0.20 (64bit) on [Sun Apr 10 20:07:11 2022] ***
compiled with version: 11.2.0 on 19 February 2022 11:05:58
os: Linux-5.13.0-39-generic #44-Ubuntu SMP Thu Mar 24 15:35:05 UTC 2022
nodename: WEB
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /home/dfl/deployment/testdeployment
detected binary path: /usr/local/bin/uwsgi
chdir() to /home/dfl/deployment/testdeployment
your processes number limit is 55102
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to TCP address 127.0.0.1:9001 fd 3
Python version: 3.9.7 (default, Sep 10 2021, 14:59:43)  [GCC 11.2.0]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x558490fb5240
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 218712 bytes (213 KB) for 2 cores
*** Operational MODE: preforking ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x558490fb5240 pid: 555000 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 555000)
spawned uWSGI worker 1 (pid: 555001, cores: 1)
spawned uWSGI worker 2 (pid: 555002, cores: 1)
[pid: 555002|app: 0|req: 1/1] 192.168.1.17 () {46 vars in 895 bytes} [Sun Apr 10 12:17:19 2022] GET / => generated 508 bytes in 24 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555002|app: 0|req: 2/2] 192.168.1.11 () {46 vars in 875 bytes} [Sun Apr 10 12:17:39 2022] GET / => generated 508 bytes in 1 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555001|app: 0|req: 1/3] 192.168.1.7 () {40 vars in 656 bytes} [Sun Apr 10 12:19:14 2022] GET / => generated 508 bytes in 22 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555002|app: 0|req: 3/4] 192.168.1.7 () {40 vars in 656 bytes} [Sun Apr 10 12:20:15 2022] GET / => generated 508 bytes in 3 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555002|app: 0|req: 4/5] 192.168.1.7 () {40 vars in 656 bytes} [Sun Apr 10 12:20:16 2022] GET / => generated 508 bytes in 0 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555001|app: 0|req: 2/6] 192.168.1.17 () {44 vars in 876 bytes} [Sun Apr 10 12:59:53 2022] GET /admin/ => generated 0 bytes in 10 msecs (HTTP/1.1 302) 8 headers in 298 bytes (1 switches on core 0)
[pid: 555002|app: 0|req: 5/7] 192.168.1.17 () {44 vars in 913 bytes} [Sun Apr 10 12:59:53 2022] GET /admin/login/?next=/admin/ => generated 2212 bytes in 42 msecs (HTTP/1.1 200) 8 headers in 428 bytes (1 switches on core 0)
[pid: 555002|app: 0|req: 6/8] 192.168.1.17 () {44 vars in 864 bytes} [Sun Apr 10 13:17:01 2022] GET / => generated 508 bytes in 2 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555001|app: 0|req: 3/9] 192.168.1.11 () {46 vars in 875 bytes} [Sun Apr 10 13:18:42 2022] GET / => generated 508 bytes in 1 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555001|app: 0|req: 4/10] 192.168.1.17 () {46 vars in 895 bytes} [Sun Apr 10 13:33:33 2022] GET / => generated 508 bytes in 1 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555001|app: 0|req: 5/11] 127.0.0.1 () {60 vars in 1259 bytes} [Sun Apr 10 13:33:48 2022] GET / => generated 508 bytes in 1 msecs (HTTP/1.1 200) 4 headers in 133 bytes (1 switches on core 0)
[pid: 555001|app: 0|req: 6/12] 192.168.1.17 () {44 vars in 876 bytes} [Sun Apr 10 13:34:15 2022] GET /admin/ => generated 0 bytes in 1 msecs (HTTP/1.1 302) 8 headers in 298 bytes (1 switches on core 0)
[pid: 555002|app: 0|req: 7/13] 192.168.1.17 () {44 vars in 913 bytes} [Sun Apr 10 13:34:15 2022] GET /admin/login/?next=/admin/ => generated 2212 bytes in 6 msecs (HTTP/1.1 200) 8 headers in 428 bytes (1 switches on core 0)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/98050.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!