在 Debian 上配置 Python 服务(后台服务),常见且推荐的方式是使用 systemd。下面按从简单到规范的方式说明,适用于 Debian 10/11/12。
假设你的 Python 服务是一个长期运行的脚本,例如:
# /opt/myservice/app.py
import time
while True:
print("Service is running...")
time.sleep(5)
✅ 建议:
/opt/myservicesudo nano /etc/systemd/system/myservice.service
示例内容(✅ 非常重要):
[Unit]
Description=My Python Service
After=network.target
[Service]
Type=simple
User=myuser
WorkingDirectory=/opt/myservice
ExecStart=/opt/myservice/venv/bin/python /opt/myservice/app.py
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
| 参数 | 说明 |
|---|---|
| Type=simple | 普通脚本 |
| User | 非 root 用户(安全) |
| Restart=always | 崩溃自动重启 |
| After=network.target | 网络启动后再启动 |
sudo systemctl daemon-reload
sudo systemctl start myservice
sudo systemctl enable myservice
systemctl status myservice
journalctl -u myservice -f
cd /opt/myservice
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
ExecStart 使用:
ExecStart=/opt/myservice/venv/bin/python /opt/myservice/app.py
ExecStart=/opt/myservice/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app
然后配合 Nginx 反向代理(生产环境标准做法)。
journalctl -u myservice --no-pager
sudo chown -R myuser:myuser /opt/myservice
确认:
which python3
/opt/myservice/venv/bin/python --version
nohup python3 app.py > output.log 2>&1 &
✅ 生产环境标准做法
如果你愿意,可以告诉我:
我可以帮你写 完全可用的服务文件。