温馨提示×

Ubuntu Python项目部署指南

小樊
39
2025-12-24 09:56:55
栏目: 编程语言

Ubuntu Python项目部署指南

一 环境准备与基础配置

  • 更新系统并安装基础工具:sudo apt update && sudo apt install -y python3 python3-pip python3-venv git build-essential libssl-dev libffi-dev
  • 建议使用 Ubuntu 20.04/22.04 LTS,具备 SSH 访问权限与 sudo 权限
  • 创建项目目录并上传代码:git clone 或 scp -r user@ip:
  • 生成依赖清单:pip freeze > requirements.txt(开发环境),部署环境用 pip install -r requirements.txt 安装

二 运行方式与服务器选型

  • 开发/调试:python app.py(Flask 默认仅本机访问,生产不可用)
  • WSGI(Flask/Django 常用)
    • Gunicorn:pip install gunicorn;gunicorn -w 4 -b 127.0.0.1:8000 app:app(4 个工作进程,绑定本机 8000)
    • uWSGI:pip install uwsgi;uwsgi --http :8000 --module your_project.wsgi
  • ASGI(异步/Channels)
    • Daphne:pip install daphne;daphne -b 0.0.0.0 -p 8000 your_project.asgi:application
  • 选型建议:中小规模优先 Gunicorn + Nginx;高并发/复杂协议可用 uWSGI;含 WebSocket/异步ASGI(Daphne)

三 反向代理与静态资源

  • 安装 Nginx:sudo apt install -y nginx
  • 站点配置示例(/etc/nginx/sites-available/yourapp)
    • 反向代理到 WSGI/ASGI:
      • 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; } }
    • 静态文件(可选,提高性能):location /static/ { alias /path/to/static/; }
  • 启用站点与热重载:sudo ln -s /etc/nginx/sites-available/yourapp /etc/nginx/sites-enabled/;sudo nginx -t && sudo systemctl reload nginx

四 进程守护与开机自启

  • 使用 systemd 管理 Gunicorn(推荐)
    • /etc/systemd/system/gunicorn.service
      • [Unit] Description=Gunicorn instance; After=network.target
      • [Service] User=www-data; Group=www-data; WorkingDirectory=/path/to/app; Environment=“PATH=/path/to/app/venv/bin”; ExecStart=/path/to/app/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock app:app
      • [Install] WantedBy=multi-user.target
    • 启动与开机自启:sudo systemctl daemon-reload && sudo systemctl enable --now gunicorn && sudo systemctl status gunicorn
  • 使用 systemd 管理 uWSGI(可选)
    • ExecStart=/path/to/venv/bin/uwsgi --ini /path/to/yourproject/wsgi.ini
    • 常见 uWSGI 配置要点:module=wsgi:app; master=true; processes=4; socket=/run/yourapp.sock; chmod-socket=660; vacuum=true

五 安全与运维要点

  • 防火墙:sudo ufw allow OpenSSH;sudo ufw allow ‘Nginx Full’;sudo ufw enable
  • HTTPS:sudo apt install -y certbot python3-certbot-nginx;sudo certbot --nginx -d your_domain(自动申请并配置 Let’s Encrypt)
  • 日志与排错
    • 查看服务:sudo journalctl -u gunicorn -f;sudo tail -f /var/log/nginx/error.log
    • Nginx 配置检查:sudo nginx -t
  • 数据库(如 MySQL/PostgreSQL):安装与初始化;Django 在 settings.py 配置 DATABASES;执行迁移 python manage.py migrate
  • 备份与恢复
    • MySQL:mysqldump -u user -p db > backup.sql;恢复:mysql -u user -p db < backup.sql
    • PostgreSQL:pg_dump -U user db > backup.dump;恢复:pg_restore -U user -d db backup.dump
  • 安全建议:最小权限运行(专用用户与组)、仅开放 80/443、定期更新系统与依赖、密钥/环境变量妥善管理

0