CentOS部署Python项目核心流程如下:
安装基础环境
sudo yum update -y
sudo yum install python3 python3-pip -y # 安装Python和pip
创建虚拟环境
python3 -m venv myenv # 创建虚拟环境
source myenv/bin/activate # 激活环境
安装项目依赖
pip install -r requirements.txt # 通过requirements.txt安装依赖
启动应用程序
python app.py # 假设入口文件为app.py
pip install gunicorn
gunicorn -w 4 -b 127.0.0.1:8000 app:app # 指定工作进程和监听端口
配置系统服务(可选)
创建/etc/systemd/system/myapp.service
文件:
[Unit]
Description=My Python App
After=network.target
[Service]
User=your_user
WorkingDirectory=/path/to/app
ExecStart=/path/to/app/venv/bin/gunicorn -w 4 -b 127.0.0.1:8000 app:app
Restart=always
[Install]
WantedBy=multi-user.target
启用并启动服务:
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp
配置防火墙与反向代理(可选)
sudo firewall-cmd --permanent --add-port=8000/tcp
sudo firewall-cmd --reload
/etc/nginx/conf.d/myapp.conf
:server {
listen 80;
server_name your_domain.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
}
重启Nginx:sudo systemctl reload nginx
验证部署
访问http://服务器IP:端口
,确认应用正常运行。
可选优化:
logrotate
)和监控工具(如top
、vmstat
)。