體系一:Systemd(現代標準,CentOS 7+/Ubuntu 16.04+/Debian 8+)
服務單元文件 /etc/systemd/system/myapp.service
[Unit]
Description=My Custom Service
After=network.target
[Service]
Type=simple
User=www
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/start.sh
Restart=on-failure
RestartSec=5
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
管理命令
systemctl daemon-reload
systemctl enable --now myapp # 立即啟用並開機自啟
systemctl status myapp
journalctl -u myapp -f # 查看日誌
體系二:SysVinit / chkconfig(舊版 CentOS 6/Ubuntu 14.04)
腳本規範 /etc/init.d/myapp
#!/bin/bash
# chkconfig: 2345 85 15
# description: My Custom Service
. /etc/init.d/functions
start() { /opt/myapp/bin/start.sh; }
stop() { /opt/myapp/bin/stop.sh; }
case "$1" in
start) start;;
stop) stop;;
restart) stop; start;;
status) status myapp;;
*) echo "Usage: $0 {start|stop|restart|status}"; exit 1;;
esac
註冊與管理
chmod +x /etc/init.d/myapp
chkconfig --add myapp
chkconfig --level 2345 myapp on
service myapp start
體系三:rc.local(簡單粗暴,兼容所有)
chmod +x /etc/rc.d/rc.local
echo "/opt/myapp/bin/start.sh" >> /etc/rc.d/rc.local
# systemd系統需確保 rc-local 服務啟用
systemctl enable --now rc-local
體系四:用戶級定時/啟動
crontab @reboot
crontab -e
@reboot /home/user/bin/start.sh >> /home/user/logs/start.log 2>&1
systemd user服務(圖形登入/長運行用戶進程)
mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/myapp.service <<'EOF'
[Unit]
Description=My User Service
[Service]
ExecStart=/home/user/bin/start.sh
Restart=always
[Install]
WantedBy=default.target
EOF
systemctl --user enable --now myapp
loginctl enable-linger user # 允許用戶非登入狀態運行服務
體系五:一次性定時任務
at 02:30 tomorrow
at> /home/user/bin/backup.sh
at>
# 查看隊列:atq;刪除:atrm
避坑指南
- 腳本必須可執行(
chmod +x)且Shebang正確(#!/bin/bash)。
- 環境變量極少(無
PATH、HOME),腳本內全路徑調用命令/文件。
- 長運行進程用
Type=simple+Restart=on-failure,前台運行勿daemonize。
- 需網絡/存儲就緒後啟動 →
After=network-online.target remote-fs.target + systemctl enable systemd-networkd-wait-online。
- SELinux啟用時,自定義腳本需
chcon -t bin_t /path/script或編寫策略模組。