在 CentOS 服务器上部署 Django 项目的踩坑记录:本地导出依赖库、拆分开发与生产两套 setting、收集静态资源,服务器上安装 MySQL 与 Python3、建虚拟环境、克隆代码,最后用 uwsgi + nginx 对外提供服务。

这一篇的部署操作当时是失败的,成功的方案见 Django项目部署。

1. 服务器与域名相关

  • 找一台具有公网 IP 的服务器

该网站搭建采用的是阿里云的服务器以及域名解析相关服务,该部分需要自己花钱购买

2. Django 本地项目修改

导出 Python 的依赖库

1
pip freeze > requirements.txt
image-20250304141856802

创建两个不同的 setting 配置文件

由于代码的测试和运行在不同的主机下,并且测试与运行的需要的配置可能不同,比如数据库的名称和用户的账号密码等都可能不同。所以我们需要创建两个不同的 setting 文件,根据环境不同自动选择运行配置。

静态资源收集

  • 在开发过程中,配置文件 DEBUG 状态为:

    1
    2
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    • 此时 Django 会自动帮助我们完成静态资源的分发,但在项目部署到服务器运行后,DEBUG=False

    • 在服务器上我们使用 nginx 做静态文件的分发

    • 在 Django 服务器配置文件上加上:

      1
      2
      3
      4
      5
      STATIC_URL = '/static/'
      STATICFILES_DIRS = [
      os.path.join(BASE_DIR, "static"),
      ]
      STATIC_ROOT = os.path.join(BASE_DIR, "static") # 收集至static文件夹

      运行以下命令,Django 就会自动帮我们收集静态文件至上面的 staticfiles 文件夹(文件夹名称可以自定义设置)

      1
      python manage.py collectstatic

      导出数据库:

      1
      mysqldump -u root -p huapidb > huapidb.sql

将数据提交至远程仓库

3. 服务器环境配置

下载以下软件:

1
2
3
4
git
python
mysql
nginx

安装命令:

1
2
yum install git -y
yum install nginx -y

开放端口

必备端口:22(SSH),80/443(http/https),3306(mysql)

  • 查看防火墙开放的端口:

    1
    firewall-cmd --list-ports
    • 运行结果

      image-20250418154813794
      • 8888/8000:通常用于测试端口,比如Django项目的测试等
  • 关闭某个端口:

    1
    firewall-cmd --remove-port=45678/tcp --permanent
    • --permanent:添加此参数后此端口永远关闭,否则知识暂时关闭
  • 开启某个端口

    1
    firewall-cmd --add-port=3306/tcp --permanent
    • 如果只是希望自己的内部项目使用 MySQL 数据库,那么就不需要开启相应端口
  • 重启防火墙:

    1
    firewall-cmd --reload
    • 在执行开放或关闭某个端口的代码后执行,应用更改后的设置
  • 检查那些端口正在被监听

    1
    ss -tunlp

在服务器网页端也需要配置防火墙的开启端口

image-20250418160934258

拉取代码

在服务器上拉取我们提交至 Github 上的代码,这里我用的是 SSH 进行拉取,存放到 /www/wwwroot/ 文件夹下

image-20250304195826093

创建 python 虚拟环境

安装 virtualenv

1
pip install virtualenv

image-20250304200458605

创建虚拟环境

1
virtualenv env

image-20250304200711896

  • 注意在项目文件夹下创建虚拟环境

激活虚拟环境

1
source env/bin/activate

image-20250304200906233

下载第三方模块

1
pip install -r requirements.txt
  • 这里就用到了之前导出的依赖文件

导入数据库

首先在服务器端要存在一个数据库,进入数据库

1
mysql -u root -p
image-20250304201413252

创建数据库

1
create database huapidb DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  • huapidb 替换为你的数据库名称
  • 其实这里创建数据库的操作,读者在自己的本机上已经运行过一次了,个人推荐最好使用在本机上创建数据库的方式进行创建即可,可以保证创建的数据库类型一致
1
show databases;
  • 展示当前的数据库,确保已经创建成功

image-20250304201814397

  • 关于更多的数据库相关操作,可以参考其他教程

导入数据/创建表

1
2
use huapidb;
source huapidb.sql;

这里我导入数据出现了一些问题,因此可以重新创建一张表

1
python manage.py makemigrations

可能出现的错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(HuaPiServer_env) [root@iZ2zebypmucnsapoka2mpiZ HuaPiServer]# python manage.py makemigrations
Traceback (most recent call last):
File "/www/wwwroot/HuaPiServer/HuaPiServer_env/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 16, in <module>
import MySQLdb as Database
File "/www/wwwroot/HuaPiServer/HuaPiServer_env/lib/python3.11/site-packages/MySQLdb/__init__.py", line 17, in <module>
from . import _mysql
ImportError: /www/wwwroot/HuaPiServer/HuaPiServer_env/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-x86_64-linux-gnu.so: undefined symbol: mysql_character_set_name

File "/www/server/pyporject_evn/versions/3.11.5/lib/python3.11/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/www/wwwroot/HuaPiServer/HuaPiServer_env/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 18, in <module>
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

重新安装 mysqlclient :

1
pip install --no-cache-dir --force-reinstall mysqlclient

报错:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(HuaPiServer_env) [root@iZ2zebypmucnsapoka2mpiZ HuaPiServer]# pip install --no-cache-dir --force-reinstall mysqlclient
Looking in indexes: https://mirrors.aliyun.com/pypi/simple
Collecting mysqlclient
Downloading https://mirrors.aliyun.com/pypi/packages/61/68/810093cb579daae426794bbd9d88aa830fae296e85172d18cb0f0e5dd4bc/mysqlclient-2.2.7.tar.gz (91 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error

File "<string>", line 156, in <module>
File "<string>", line 49, in get_config_posix
File "<string>", line 28, in find_package_name
Exception: Can not find valid pkg-config name.
Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
  • 12 行:

    1
    Exception: Can not find valid pkg-config name.

    安装 mariadb-devel

    1
    sudo yum install -y mariadb-devel

    检查 pkg-config

    1
    pkg-config --version
    1
    2
    (HuaPiServer_env) [root@iZ2zebypmucnsapoka2mpiZ HuaPiServer]# pkg-config --version
    0.27.1

重新安装 mysqlclient 成功

执行 makemigrations

1
2
3
4
5
6
7
(HuaPiServer_env) [root@iZ2zebypmucnsapoka2mpiZ HuaPiServer]# python manage.py makemigrations
System check identified some issues:

WARNINGS:
?: (staticfiles.W004) The directory '/www/wwwroot/HuaPiServer/static' in the STATICFILES_DIRS setting does not exist.

django.db.utils.NotSupportedError: MySQL 8.0.11 or later is required (found 5.7.44).
  • 这里是 Django 的问题,Django 版本过高,只支持 8.0 以上的版本

    我选择重新安装较低的 Django 版本

    1
    pip install "django<4.2"

最后执行:

1
2
python manage.py makemigrations
python manage.py migrate

检查数据库:

1
show tables
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
mysql> use huapidb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_huapidb |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
| main_articlepartition |
| main_user |
+----------------------------+
12 rows in set (0.00 sec)

证明数据库创建成功

试运行

1
python manage.py runserver 172.31.140.19:8000

在自己计算机的浏览器上输入:

1
x.x.x.x:8000
  • x.x.x.x:服务器的 ip 地址

如果出现如下信息,没有加载出网页:

image-20250304222636049

1
2
3
4
5
6
7
8
DisallowedHost at /
Invalid HTTP_HOST header: '60.205.182.51:8000'. You may need to add '60.205.182.51' to ALLOWED_HOSTS.
Request Method: GET
Request URL: http://60.205.182.51:8000/
Django Version: 4.1.13
Exception Type: DisallowedHost
Exception Value:
Invalid HTTP_HOST header: '60.205.182.51:8000'. You may need to add '60.205.182.51' to ALLOWED_HOSTS.

需要在 settings.py 中 ALLOWED_HOSTS 列表中添加自己的服务器 IP

大概在文件的 20-30 行的位置

1
ALLOWED_HOSTS = ["60.205.182.51", "127.0.0.1", "localhost"]

uwsgi 部署

安装 uwsgi

1
pip install uwsgi

创建 uwsgi 的配置文件

1
vim uwsgi.ini

创建日志文件

1
2
mkdir logs
vim logs/error.log

复制以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[uwsgi]
# 开启主进程
master = true
# 指定uwsgi工作的进程数
processes = 4
# 指定工作的每个进程下的线程数
threads = 2
# 指定项目的目录
chdir = /www/wwwroot/HuaPiServer
# wsgi.py文件的位置
wsgi-file= %(chdir)/HuaPiServer/wsgi.py
# 使用nginx这里就要用socket
socket = 127.0.0.1:8888
# 日志
logto = %(chdir)/logs/error.log
chmod-socket = 660
vacuum = true
max-requests = 1000
# uwsgi的运行状态
stats=%(chdir)/uwsgi.status
# uwsgi的进程id
pidfile=%(chdir)/uwsgi.pid

运行配置文件

1
uwsgi --ini uwsgi.ini

image-20250304220646619

停止 uwsgi

1
2
3
uwsgi --stop uwsgi.pid
# 或
pkill -f uwsgi -9

重启

1
uwsgi --reload uwsgi.pid

退出

Ctrl + C

nginx 配置

去对应域名控制台做域名解析,解析到当前的服务器

image-20250304221242705

  • 主要就是将域名指向自己的服务器的 IP

以下操作可以在另一个标签页下进行(上一个被 uwsgi 占用)

image-20250304221609864

转到 nginx 安转目录下

1
cd /etc/nginx/

修改 nginx.conf 内容

1
vim nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
# nginx配置

server {
listen 80;
server_name www.huapi2d.xyz;
location / {
uwsgi_pass 127.0.0.1:24680; # uwsgi运行的端口
include uwsgi_params;
}
location /static{
alias /www/wwwroot/HuaPiServer/static; # 你收集的静态文件的位置
}
}

建议在宝塔面板里修改文件内容

当然如果还有其他的资源文件,比如我习惯于将用户上传的文件存储在 media 文件夹下,那么也需要将资源文件目录添加到 nginx.conf 文件中,书写格式如下:

1
2
3
4
location /media/ {
alias /www/wwwroot/HuaPiServer/media/;
autoindex on;
}

重启 nginx

1
nginx -s reload