讓指定程式/腳本在 Linux 開機自動運行,主流有兩種方式:傳統 rc.local 相容法與現代 systemd 服務單元 法。
/etc/rc.local (相容舊習慣,簡單直接)chmod +x /etc/rc.localexit 0 前加入啟動命令 (需使用絕對路徑):vim /etc/rc.local#!/bin/bash
# 範例:啟動 LAMP 堆疊與 Tomcat
/opt/lampp/lampp start
/usr/local/tomcat/bin/startup.sh
exit 0
注意: 部分發佈版 (如 CentOS 7+, Ubuntu 16.04+) 預設 rc-local.service 可能未啟用,需執行:systemctl enable rc-local.service (或 rc.local 視發佈版而定)。
建議生產環境使用此法。以自訂腳本 /opt/scripts/myapp.sh 為例:
vim /etc/systemd/system/myapp.service
[Unit]
Description=My Custom Application
After=network.target mysql.service # 依賴關係:網路就緒、MySQL 啟動後再啟動
[Service]
Type=simple # 或 forking (若腳本背景化)
User=www-data # 執行身分 (非 root 更安全)
WorkingDirectory=/opt/myapp
ExecStart=/opt/scripts/myapp.sh # 啟動命令 (絕對路徑)
Restart=on-failure # 失敗自動重啟
RestartSec=5 # 重啟間隔 5 秒
StandardOutput=journal # 輸出到 journald
StandardError=journal
[Install]
WantedBy=multi-user.target # 多用戶模式 (含圖形/文字) 啟動
systemctl daemon-reload
systemctl enable myapp.service
systemctl start myapp.service # 立即啟動測試
systemctl status myapp.service # 查看狀態
journalctl -u myapp.service -f # 即時追蹤日誌
若需「開機後每小時執行」而非「開機執行一次」,請建立 myapp.timer:
[Unit]
Description=Run myapp hourly
[Timer]
OnBootSec=5min # 開機 5 分鐘後首次執行
OnUnitActiveSec=1h # 之後每小時執行
Persistent=true # 若關機錯過時間,開機後補跑
[Install]
WantedBy=timers.target
啟用:systemctl enable --now myapp.timer
| 場景 | 推薦方式 |
|---|---|
| 簡單腳本、臨時測試、相容舊系統 | /etc/rc.local |
| 正式服務、需依賴管理、自動重啟、日誌整合、非 root 執行 | systemd Service Unit |
| 定時/週期性任務 | systemd Timer (現代) 或 Cron (傳統) |