在 Ubuntu 上部署 Python Web 框架的标准流程
面向 Flask、Django 等主流框架,生产环境通常采用 WSGI 服务器(Gunicorn 或 uWSGI)+ Nginx 反向代理,并通过 systemd 守护进程保证常驻运行。若使用 ASGI 框架(如 FastAPI、Starlette),应改用 Uvicorn/Hypercorn 作为 ASGI 服务器,Nginx 配置思路一致。该组合可提供静态资源高效服务、并发处理与进程守护能力。
一、准备与部署通用步骤
sudo apt update && sudo apt install -y python3 python3-pip python3-venv git build-essential libssl-dev libffi-devgit clone <repo> && cd <project>scp -r <本地目录> <user>@<ip>:/path/to/apppython3 -m venv venv && source venv/bin/activatepip install -r requirements.txtsudo ufw allow 'Nginx Full'(同时保证 22 端口用于 SSH)app.run())。二、以 Gunicorn + Nginx 部署(Flask 示例)
pip install gunicorngunicorn -w 4 app:app(先在本地或内网验证)sudo nano /etc/systemd/system/myflaskapp.service[Unit]
Description=My Flask Application
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/path/to/your/flask/app
Environment="PATH=/path/to/your/flask/app/venv/bin"
ExecStart=/path/to/your/flask/app/venv/bin/gunicorn -w 4 app:app
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload && sudo systemctl start myflaskapp && sudo systemctl enable myflaskappsudo apt install nginxsudo nano /etc/nginx/sites-available/defaultserver {
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 nginx -t && sudo systemctl reload nginx三、以 uWSGI + Nginx 部署(Django 示例)
pip install uwsgipython manage.py collectstatic --noinputnano myapp_uwsgi.ini[uwsgi]
module = myproject.wsgi:application
master = true
processes = 4
socket = /run/gunicorn.sock
chmod-socket = 660
vacuum = true
die-on-term = true
sudo nano /etc/systemd/system/myuwsgi.service[Unit]
Description=uWSGI instance to serve myproject
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/path/to/myproject
Environment="PATH=/path/to/myproject/venv/bin"
ExecStart=/path/to/myproject/venv/bin/uwsgi --ini myapp_uwsgi.ini
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload && sudo systemctl start myuwsgi && sudo systemctl enable myuwsgiserver {
listen 80;
server_name myproject.example.com;
location / {
include uwsgi_params;
uwsgi_pass unix:/run/gunicorn.sock;
}
location /static {
alias /path/to/myproject/static;
}
}
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/ && sudo nginx -t && sudo systemctl reload nginx四、可选优化与安全加固
sudo apt install certbot python3-certbot-nginx -ysudo certbot --nginx -d yourdomain.comsudo journalctl -u myflaskapp -f、sudo journalctl -u myuwsgi -f/var/log/nginx/access.log、/var/log/nginx/error.loglocation /static 提供服务;用户上传的 MEDIA_ROOT 亦建议由 Nginx 直接托管并设置合适的访问权限。