萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 設定開機自動啟動服務/腳本:rc.local 與 systemd 兩大法

讓指定程式/腳本在 Linux 開機自動運行,主流有兩種方式:傳統 rc.local 相容法與現代 systemd 服務單元 法。

方法一:/etc/rc.local (相容舊習慣,簡單直接)

  1. 確保檔案存在且可執行:
    chmod +x /etc/rc.local
  2. 編輯檔案,在 exit 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 視發佈版而定)。

方法二:systemd 服務單元 (標準、功能完整、支援依賴/重啟/日誌)

建議生產環境使用此法。以自訂腳本 /opt/scripts/myapp.sh 為例:

1. 建立服務單元檔

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           # 多用戶模式 (含圖形/文字) 啟動

2. 重載 systemd 並啟用開機自啟

systemctl daemon-reload
systemctl enable myapp.service
systemctl start myapp.service        # 立即啟動測試
systemctl status myapp.service       # 查看狀態
journalctl -u myapp.service -f       # 即時追蹤日誌

進階:Systemd Timer 替代 Cron 定時任務

若需「開機後每小時執行」而非「開機執行一次」,請建立 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 (傳統)
copyright © 萬盛學電腦網 all rights reserved