在 Linux 系統管理中,將自行開發或第三方的可執行程式註冊為系統服務,並設定開機自動啟動,是確保服務穩定運行的關鍵步驟。本文將介紹兩種主流且通用的實作方法,幫助您輕鬆完成服務化部署。
/etc/rc.local 實現開機自啟(傳統相容法)這是最直觀、跨發行版相容性最好的方式,適合簡單的腳本或程式啟動需求。
/etc/rc.local 檔案:vim /etc/rc.localexit 0 之前,新增您的程式啟動指令(請使用絕對路徑),例如:/opt/myapp/bin/start_server.sh &chmod +x /etc/rc.local注意:部分新版系統(如 CentOS 7+、Ubuntu 16.04+)預設可能未啟用 rc-local 服務,需執行 systemctl enable rc-local 並啟動它。
將程式封裝為 /etc/init.d/ 下的服務腳本,可支援 start、stop、restart、status 等標準操作,並自動納入開機啟動序列。
/etc/init.d/ 目錄,或建立軟連結:cp /path/to/your_program /etc/init.d/myappln -s /path/to/your_program /etc/init.d/myappstart 和 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
esacchmod +x /etc/init.d/myappchkconfig --add myappchkconfig myapp on對於採用 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-reloadsystemctl enable myapp.servicesystemctl start myapp.service
rc.local 最快上手。/etc/init.d/ 腳本。journalctl -u myapp 或 /var/log/messages)排除問題。