CentOS 上部署 Python 应用的实用步骤
一 准备与安装
- 更新系统并安装基础软件包:sudo yum update -y && sudo yum install -y python3 python3-pip git nginx
- 确认版本:python3 --version、pip3 --version
- 创建并激活虚拟环境:python3 -m venv venv && source venv/bin/activate
- 安装依赖:pip install -r requirements.txt
- 说明:CentOS 7 默认带 Python 2.7,生产建议使用 Python 3.x 并通过虚拟环境隔离依赖。
二 Web 应用部署流程
- 安装并启动 Nginx:sudo yum install -y nginx && sudo systemctl start nginx && sudo systemctl enable nginx
- 使用 Gunicorn 启动应用(示例为 Flask,应用对象为 app:app):pip install gunicorn && gunicorn -w 4 -b 127.0.0.1:8000 app:app
- 配置 Nginx 反向代理(/etc/nginx/conf.d/myapp.conf):
- 示例:
- server { listen 80; server_name your_domain_or_ip;
- location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
- 使配置生效:sudo systemctl reload nginx
- 开放防火墙:sudo firewall-cmd --permanent --zone=public --add-service=http && sudo firewall-cmd --permanent --zone=public --add-service=https && sudo firewall-cmd --reload
- 访问测试:浏览器打开服务器 IP/域名 验证页面是否正常。
三 以 systemd 托管进程
- 创建服务文件:sudo vi /etc/systemd/system/myapp.service
- 示例内容(按需替换路径与参数):
- [Unit] Description=gunicorn daemon for myapp; After=network.target
- [Service] User=your_username; Group=nginx; WorkingDirectory=/path/to/your/app; Environment=“PATH=/path/to/your/app/venv/bin”; ExecStart=/path/to/your/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 systemctl status myapp;查看日志 sudo journalctl -u myapp -f。
四 脚本类任务与后台服务
- 适用场景:定时任务、队列消费者、数据同步脚本等长期运行或守护进程。
- 方式一:使用 systemd 托管脚本
- 创建服务文件:sudo vi /etc/systemd/system/myscript.service
- 示例要点:
- [Unit] Description=My Python Script; After=network.target
- [Service] User=your_username; Group=your_group; WorkingDirectory=/path/to/script; ExecStart=/path/to/venv/bin/python /path/to/script/app.py; Restart=always
- [Install] WantedBy=multi-user.target
- 启动:sudo systemctl daemon-reload && sudo systemctl start myscript && sudo systemctl enable myscript
- 方式二:通过启动脚本封装(start_script.sh),再由 systemd 调用,便于做环境准备与日志重定向。
五 安全与优化建议
- 不要使用 Flask/Django 内置开发服务器在生产环境对外提供访问,使用 Gunicorn/uWSGI 作为 WSGI 服务器,Nginx 作为反向代理与静态资源服务。
- 配置 HTTPS:安装 certbot 并获取免费证书,一键配置 Nginx:sudo yum install -y certbot python3-certbot-nginx && sudo certbot --nginx -d your_domain_or_ip(按提示完成验证与自动续期)。
- 静态文件:由 Nginx 直接托管(示例:location /static { alias /path/to/static; }),减轻应用负载。
- 进程与资源:根据 CPU 核心数 与内存合理设置 Gunicorn 工作进程数(如 -w 4),并配置超时、最大请求数等参数;为服务设置专用系统用户并最小权限运行。
- 日志与监控:应用与 Nginx 均输出到日志文件,结合 systemd 与日志轮转(logrotate)做长期留存与告警。