在 Debian 上部署 Python Web 应用的推荐做法
使用 Nginx + Gunicorn + systemd 是生产环境的主流方案:Nginx 负责反向代理与静态资源,Gunicorn 作为 WSGI 服务器承载应用,systemd 保证进程常驻与开机自启。下面给出可直接落地的步骤与要点。
一 准备与安装
sudo apt update && sudo apt upgrade -ysudo apt install python3 python3-pip python3-venv nginx -ypython3 -m venv venv && source venv/bin/activatepip install -r requirements.txt(示例依赖:Flask/Gunicorn)。二 以 Flask 为例的最小可用部署
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello, Flask on Debian!"
if __name__ == '__main__':
app.run()
venv/bin/gunicorn -b 127.0.0.1:8000 app:appbind = '127.0.0.1:8000'
workers = 3
启动:venv/bin/gunicorn -c gunicorn_config.py app:appserver {
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 ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabledsudo nginx -t && sudo systemctl reload nginx三 使用 systemd 托管 Gunicorn
[Unit]
Description=Gunicorn daemon for myproject
After=network.target
[Service]
User=your_username
Group=www-data
WorkingDirectory=/path/to/myproject
ExecStart=/path/to/myproject/venv/bin/gunicorn -c /path/to/myproject/gunicorn_config.py app:app
Restart=always
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reloadsudo systemctl start myproject && sudo systemctl enable myprojectsudo journalctl -u myproject -fsudo systemctl reload myprojectsudo systemctl reload nginx。四 安全与网络配置
sudo ufw allow 'Nginx Full' && sudo ufw enablesudo apt install certbot python3-certbot-nginx -ysudo certbot --nginx -d your_domain_or_iplocation /static/ {
alias /path/to/myproject/static/;
expires 1y;
add_header Cache-Control "public, immutable";
}
五 其他可选方案与排错要点
FROM nginx:latest
COPY . /usr/share/nginx/html
EXPOSE 80
构建与运行:docker build -t mywebapp . && docker run -d -p 80:80 mywebapp。如需域名与证书,可在宿主机再用 Nginx 反代或配合 Certbot。systemctl status myproject、journalctl -u myproject -fsudo nginx -t、sudo systemctl reload nginxss -tlnp | grep ':80\|:8000',云服务器安全组/防火墙放行 80/443