LinuxMastery By asdlkfj

LinuxMastery 15: 服務總管 systemctl

掌控服務的生老病死

在現代 Linux (CentOS 7+, Ubuntu 16.04+),Systemd 是系統初始化的標準。它負責管理系統啟動後的各種服務 (Daemons)。你需要熟練使用 systemctl 指令來管理這些背景程式。

核心指令詳解

假設我們要管理 nginx 服務:

  1. 狀態管理

    • 啟動systemctl start nginx
    • 停止systemctl stop nginx
    • 重啟systemctl restart nginx (會中斷連線)
    • 重新載入設定systemctl reload nginx (不會中斷連線,修改設定檔後推薦用這個)
    • 查看狀態systemctl status nginx (除錯第一步,看它是有在跑 (active running) 還是掛了 (failed))
  2. 開機啟動管理

    • 設定開機自啟systemctl enable nginx (這很重要,不然重開機後服務不會跑)
    • 取消開機自啟systemctl disable nginx

實戰心法

systemctl start 失敗時,終端機通常只會顯示 "Job failed"。這時候請依序做兩件事:

  1. systemctl status nginx:看最後幾行的錯誤訊息。
  2. journalctl -xe:查看更詳細的系統日誌。

此外,你可以用 systemctl list-unit-files --type=service 查看系統中所有服務的開機啟動狀態 (enabled/disabled)。