CentOS部署Python項目核心流程如下:
安裝基礎環境
sudo yum install python3 python3-pip # 安裝Python和pip
創建虛擬環境
python3 -m venv myenv # 創建虛擬環境
source myenv/bin/activate # 激活環境
安裝項目依賴
pip install -r requirements.txt # 通過requirements.txt安裝依賴
啟動應用服務
python app.py # 或 gunicorn/wsgi 啟動
pip install gunicorn
gunicorn -w 4 app:app # -w 指定工作進程數
配置系統服務(可選)
創建/etc/systemd/system/myproject.service
文件:
[Unit]
Description=My Python Project
After=network.target
[Service]
User=your_user
WorkingDirectory=/path/to/project
ExecStart=/path/to/project/venv/bin/gunicorn --bind 127.0.0.1:8000 app:app
Restart=always
[Install]
WantedBy=multi-user.target
然后執行:
sudo systemctl daemon-reload
sudo systemctl start myproject
sudo systemctl enable myproject
配置Nginx反向代理(可選)
sudo yum install nginx
編輯配置文件/etc/nginx/conf.d/myproject.conf
:
server {
listen 80;
server_name your_domain_or_ip;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
}
重啟Nginx:
sudo systemctl reload nginx
防火墻設置(可選)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload
說明: