ubuntu 22.04系统部署web服务器python + Django+mysql?

在 Ubuntu 22.04 上部署 Python + Django + MySQL 的 Web 服务器,最稳定且生产环境推荐的架构是:Nginx (反向X_X) + Gunicorn (WSGI 应用服务器) + MySQL (数据库)

以下是完整的从零部署指南,假设你的用户为 ubuntu(默认),项目路径为 /var/www/myproject


第一步:更新系统并安装基础依赖

首先更新软件源并安装必要的工具、Python 环境及开发库。

sudo apt update && sudo apt upgrade -y

# 安装 Python3, pip, 虚拟环境工具,以及编译 MySQL 驱动所需的开发包
sudo apt install python3-pip python3-venv python3-dev libmysqlclient-dev 
    build-essential libpq-dev mysql-server nginx git curl -y

注意:Ubuntu 22.04 自带的 MySQL 版本可能较旧或配置不同,如果生产环境对版本有要求,建议通过官方 APT 源安装特定版本的 MySQL Server,或者直接使用 apt install default-mysql-server(Debian 推荐)。这里使用默认的 mysql-server

第二步:初始化 MySQL 数据库

  1. 启动并安全配置 MySQL:

    sudo systemctl start mysql
    sudo systemctl enable mysql
    sudo mysql_secure_installation

    按照提示设置 root 密码,删除匿名用户,禁止 root 远程登录等。

  2. 创建数据库和用户:
    登录 MySQL 命令行:

    sudo mysql

    执行以下 SQL(请将密码替换为你的强密码):

    CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'your_strong_password';
    GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost';
    FLUSH PRIVILEGES;
    EXIT;

第三步:创建项目目录与虚拟环境

为了隔离依赖,建议使用 Python 虚拟环境。

# 创建项目目录
sudo mkdir -p /var/www/myproject
cd /var/www/myproject

# 创建虚拟环境
python3 -m venv venv

# 激活虚拟环境
source venv/bin/activate

# 安装 Django 和 MySQL 驱动 (mysqlclient)
pip install --upgrade pip
pip install django gunicorn mysqlclient

第四步:编写 Django 项目代码

如果你已有代码,直接上传;如果没有,创建一个示例项目结构:

django-admin startproject config .
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

关键配置 (config/settings.py):

确保数据库配置正确,并开启生产模式:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'your-secret-key-here' # 务必修改
DEBUG = False # 生产环境必须关闭

ALLOWED_HOSTS = ['your_domain.com', 'your_ip_address']

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'myuser',
        'PASSWORD': 'your_strong_password',
        'HOST': 'localhost',
        'PORT': '3306',
        'OPTIONS': {'charset': 'utf8mb4'},
    }
}

# 静态文件配置 (用于 Nginx 托管)
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

收集静态文件:

python manage.py collectstatic --noinput

第五步:配置 Gunicorn 服务

我们需要一个 systemd 服务来管理 Gunicorn,使其开机自启。

  1. 创建配置文件:

    sudo nano /etc/systemd/system/gunicorn.service
  2. 写入以下内容(请根据实际路径修改 WorkingDirectoryUser):

    [Unit]
    Description=gunicorn daemon for myproject
    After=network.target
    
    [Service]
    User=ubuntu
    Group=www-data
    WorkingDirectory=/var/www/myproject
    ExecStart=/var/www/myproject/venv/bin/gunicorn 
             --access-logfile - 
             --workers 3 
             --bind unix:/var/www/myproject/gunicorn.sock 
             config.wsgi:application
    
    [Install]
    WantedBy=multi-user.target
  3. 启动服务并设置开机自启:

    sudo chmod 644 /etc/systemd/system/gunicorn.service
    sudo systemctl daemon-reload
    sudo systemctl start gunicorn
    sudo systemctl enable gunicorn
    sudo systemctl status gunicorn

第六步:配置 Nginx 反向X_X

Nginx 负责接收用户请求,转发给 Gunicorn 处理静态文件,并将动态请求转发给 socket。

  1. 创建站点配置:

    sudo nano /etc/nginx/sites-available/myproject
  2. 写入配置(将 your_domain.com 替换为你的域名或 IP):

    server {
       listen 80;
       server_name your_domain.com your_ip_address;
    
       # 静态文件
       location /static/ {
           alias /var/www/myproject/staticfiles/;
       }
    
       # 媒体文件
       location /media/ {
           alias /var/www/myproject/media/;
       }
    
       # 转发给 Gunicorn Socket
       location / {
           include proxy_params;
           proxy_pass http://unix:/var/www/myproject/gunicorn.sock;
       }
    }
  3. 启用站点并测试配置:

    sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
    sudo nginx -t
  4. 重启 Nginx:

    sudo systemctl restart nginx

第七步:配置防火墙 (UFW)

Ubuntu 默认开启了 UFW,需要放行 HTTP 和 SSH。

sudo ufw allow 'Nginx Full'
sudo ufw allow OpenSSH
sudo ufw enable

第八步:验证部署

  1. 访问 http://your_ip_addresshttp://your_domain.com
  2. 你应该能看到 Django 的欢迎页面或你的网站内容。
  3. 检查后台:http://your_ip_address/admin 确认数据库连接正常。

补充建议:HTTPS (SSL)

生产环境强烈建议使用 HTTPS。可以使用 Certbot 免费获取 Let’s Encrypt 证书:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain.com

运行后,Certbot 会自动修改 Nginx 配置并重定向 HTTP 到 HTTPS。

常见问题排查

  • Gunicorn 无法启动:检查日志 journalctl -u gunicorn,常见原因是 collectstatic 未执行或权限问题(确保 ubuntu 用户有读写 staticfilesmedia 目录的权限)。
  • MySQL 连接错误:如果是 Can't connect to local MySQL server through socket,通常是因为 mysqlclient 没有安装好,或者 settings.py 中的 HOST 填错了(本地应填 localhost 而不是 127.0.0.1)。
  • 静态文件不显示:检查 Nginx 配置中的 alias 路径是否正确,以及文件是否存在于 STATIC_ROOT 目录下。
未经允许不得转载:CLOUD技术博 » ubuntu 22.04系统部署web服务器python + Django+mysql?