sudo yum install -y python3 python3-pip
python3 --version # 确认Python版本(建议3.6+)
pip3 --version # 确认pip版本
mkdir -p /opt/python_project && cd /opt/python_project
python3 -m venv venv # 创建虚拟环境
source venv/bin/activate # 激活虚拟环境(激活后命令行前缀为“(venv)”)
scp、rsync或Git将本地项目代码上传至服务器项目目录(如/opt/python_project)。scp -r local_project/* user@server_ip:/opt/python_project/
requirements.txt(依赖清单),通过pip安装所有依赖。pip install -r requirements.txt
pip install gunicorn
app.py中的app对象):gunicorn -w 4 -b 127.0.0.1:8000 app:app
wsgi.py文件路径:gunicorn -w 4 -b 127.0.0.1:8000 myproject.wsgi:application
-w 4(4个工作进程)、-b 127.0.0.1:8000(绑定本地8000端口,仅内部访问)。sudo yum install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
/etc/nginx/conf.d/python_project.conf,添加以下内容:server {
listen 80;
server_name your_domain.com; # 替换为域名或IP
location / {
proxy_pass http://127.0.0.1:8000; # 转发至Gunicorn
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ { # 静态文件由Nginx直接处理
alias /opt/python_project/static/;
expires 30d;
}
}
sudo nginx -t # 测试配置语法
sudo systemctl restart nginx
/etc/systemd/system/python_project.service,内容如下:[Unit]
Description=Python Project Service
After=network.target
[Service]
User=your_user # 替换为运行项目的用户(如ubuntu、centos)
Group=your_group # 替换为用户组
WorkingDirectory=/opt/python_project
ExecStart=/opt/python_project/venv/bin/gunicorn -w 4 -b 127.0.0.1:8000 app:app
Restart=always # 崩溃后自动重启
Environment="PYTHONUNBUFFERED=1" # 避免Python输出缓冲
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start python_project
sudo systemctl enable python_project # 开机自启
sudo systemctl status python_project
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload
sudo journalctl -u python_project -f # 查看Systemd服务日志
tail -f /opt/python_project/venv/log/gunicorn.log # 查看Gunicorn日志(若有)
python manage.py collectstatic将静态文件收集至STATIC_ROOT目录。workers(工作进程数,通常为CPU核心数×2+1)和threads(线程数)参数。