Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 可執行程式打造系統服務與開機自啟完整指南

編輯:Linux 教學

在 Linux 系統管理中,將自行開發或第三方的可執行程式註冊為系統服務,並設定開機自動啟動,是確保服務穩定運行的關鍵步驟。本文將介紹兩種主流且通用的實作方法,幫助您輕鬆完成服務化部署。

方法一:修改 /etc/rc.local 實現開機自啟(傳統相容法)

這是最直觀、跨發行版相容性最好的方式,適合簡單的腳本或程式啟動需求。

  1. 使用 root 權限編輯 /etc/rc.local 檔案:
    vim /etc/rc.local
  2. 在 exit 0 之前,新增您的程式啟動指令(請使用絕對路徑),例如:
    /opt/myapp/bin/start_server.sh &
  3. 確保檔案擁有執行權限:
    chmod +x /etc/rc.local

注意:部分新版系統(如 CentOS 7+、Ubuntu 16.04+)預設可能未啟用 rc-local 服務,需執行 systemctl enable rc-local 並啟動它。

方法二:建立 System V 風格初始腳本(標準服務化管理)

將程式封裝為 /etc/init.d/ 下的服務腳本,可支援 start、stop、restart、status 等標準操作,並自動納入開機啟動序列。

  1. 將可執行程式或啟動腳本複製到 /etc/init.d/ 目錄,或建立軟連結:
    cp /path/to/your_program /etc/init.d/myapp
    或
    ln -s /path/to/your_program /etc/init.d/myapp
  2. 編輯腳本,使其符合 LSB (Linux Standard Base) 標準,至少需支援 start 和 stop 參數。範例結構:
    #!/bin/bash
    # chkconfig: 2345 90 10
    # description: My Custom Application Service
    
    case "$1" in
      start)
        /opt/myapp/bin/start_server.sh
        ;;
      stop)
        /opt/myapp/bin/stop_server.sh
        ;;
      restart)
        $0 stop
        $0 start
        ;;
      *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
    esac
  3. 賦予執行權限並加入啟動項:
    chmod +x /etc/init.d/myapp
    chkconfig --add myapp
    chkconfig myapp on

現代系統建議:Systemd 服務單元

對於採用 Systemd 的現代 Linux 發行版(CentOS 7、Ubuntu 16.04、Debian 8 及更新版本),建議撰寫 .service 單元檔案放置於 /etc/systemd/system/,功能更強大、依賴管理更完善。範例:

[Unit]
Description=My Custom Application
After=network.target

[Service]
Type=simple
ExecStart=/opt/myapp/bin/start_server.sh
Restart=on-failure
User=appuser

[Install]
WantedBy=multi-user.target

然後執行:
systemctl daemon-reload
systemctl enable myapp.service
systemctl start myapp.service

總結與建議

  • 臨時/簡單任務:使用 rc.local 最快上手。
  • 生產環境標準服務:優先選擇 Systemd 單元檔,其次是 /etc/init.d/ 腳本。
  • 務必測試服務啟動、停止、重啟及開機自啟是否正常,檢查日誌(journalctl -u myapp 或 /var/log/messages)排除問題。
Copyright © Windows教程網 All Rights Reserved