在 Debian(以及其他 Linux 发行版)上“守护后台进程”,通常指确保某个程序长期稳定运行、开机自启、崩溃自动重启、日志可控。下面从「简单 → 专业」几种常见方案讲清楚。
Debian 8 以后默认使用 systemd,这是最规范、最稳定的方式。
sudo nano /etc/systemd/system/myprogram.service
示例(假设你的程序是 /opt/myprogram/run.sh):
[Unit]
Description=My Background Program
After=network.target
[Service]
ExecStart=/opt/myprogram/run.sh
WorkingDirectory=/opt/myprogram
User=myprogram
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
关键点说明:
Restart=always → 崩溃自动重启User= → 不要用 root(更安全)RestartSec → 重启间隔sudo systemctl daemon-reload
sudo systemctl enable myprogram
sudo systemctl start myprogram
systemctl status myprogram
journalctl -u myprogram -f
sudo systemctl restart myprogram
✅ 适合:生产环境、服务器、长期运行程序
nohup python3 app.py > app.log 2>&1 &
缺点:
✅ 适合:临时测试
适合:
sudo apt install supervisor
sudo nano /etc/supervisor/conf.d/myprogram.conf
[program:myprogram]
command=/opt/myprogram/run.sh
autostart=true
autorestart=true
stderr_logfile=/var/log/myprogram.err.log
stdout_logfile=/var/log/myprogram.out.log
user=myprogram
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start myprogram
✅ 适合:多程序、非 root 用户
即使进程在,也可能卡死:
if ! pgrep -f myprogram > /dev/null; then
systemctl restart myprogram
fi
或使用:
watchdogmonitMemoryMax=512M
CPUQuota=50%
sudo apt install logrotate
| 场景 | 推荐 |
|---|---|
| 服务器长期运行 | ✅ systemd |
| 临时跑一下 | nohup |
| 多程序管理 | supervisor |
| 容器环境 | Docker |
如果你愿意,可以告诉我:
我可以直接帮你写一份 可用的 service 文件。