Skip to content

部署Django

# 查看Linux系统版本
lsb_release -a

Distributor ID: Ubuntu
Description:    Ubuntu 22.04.5 LTS
Release:        22.04
Codename:       jammy

python环境搭建

sudo apt -y install python-is-python3 python3.10-venv python3-pip

# 创建虚拟环境
cd ~
mkdir .venv
cd .venv
python -m venv web
. ./web/bin/activate

# 安装Python依赖包
pip install -r requirements.txt

mysql

官方文档

# ubuntu22.04 安装 mysql 

sudo apt install mysql-server

# 修改root 用户密码
ALTER USER 'root'@'localhost' IDENTIFIED BY 'mysql';

sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
pip install mysqlclient

# 创建数据库
create database bankaccount charset=utf8;

# 创建用户
CREATE USER 'custom'@'%' IDENTIFIED BY'mysql';

# 给用户权限
GRANT ALL ON bankaccount.* TO 'custom'@'%';

# 刷新
flush privileges;

# 测试连接
mysql -ucustom -pmysql

# 删除用户
DROP USER 'custom'@'%';

django Settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bankaccount',
        'HOST': '127.0.0.1',
        'POST': '3306',
        'USER': 'custom',
        'PASSWORD': 'mysql',
    }
}

gunicorn

# 配置gunicorn
pip install gunicorn

# 创建Gunicorn服务文件
sudo vim /etc/systemd/system/gunicorn.service

# 添加内容
[Unit]  
Description=gunicorn daemon  
After=network.target  

[Service]  
User=leo
Group=leo  
WorkingDirectory=/home/leo/Desktop/thesis/bec  
ExecStart=/home/leo/.venv/web/bin/gunicorn --workers 3 --bind unix:/tmp/192.168.68.130.socket bec.wsgi:application  

[Install]  
WantedBy=multi-user.target




sudo systemctl daemon-reload  
sudo systemctl start gunicorn  
sudo systemctl enable gunicorn

# 重新加载systemd并启动Gunicorn服务

Warning: The unit file, source configuration file or drop-ins of gunicorn.service changed on disk. Run 'systemctl daemon-reload' to reload units.
警告:gunicorn的单元文件、源配置文件或插件。磁盘上的服务已更改。运行'systemctl daemon-reload'重新加载单元。

Created symlink /etc/systemd/system/multi-user.target.wants/gunicorn.service  /etc/systemd/system/gunicorn.service.

# 修改文件
sudo systemctl daemon-reload
sudo systemctl restart gunicorn.service
sudo systemctl status gunicorn.service
journalctl -u gunicorn.service -f
ps -ef | grep gunicorn

nginx

sudo vim /etc/nginx/sites-available/192.168.68.130

server {  
    listen 80;  
    server_name 192.168.68.130;  

    location = /favicon.ico { access_log off; log_not_found off;}  
    location /static/ {  
        alias /home/leo/Desktop/thesis/bec;  
    }  

    location / {  
        include proxy_params;
        proxy_pass http://unix:/tmp/192.168.68.130.socket;
    }  
}
sudo ln -s /etc/nginx/sites-available/192.168.68.130 /etc/nginx/sites-enabled
sudo systemctl status gunicorn
sudo systemctl status nginx