萬盛學電腦網

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

Systemd 服務管理完整指南:systemctl 核心指令、單元檔結構與進階除錯

Systemd 核心概念:單元

Systemd 將所有資源抽象為**單元**,以 `.service`、`.socket`、`.target`、`.mount`、`.timer` 等副檔名區分類型。服務管理核心即操作 `.service` 單元。

單元檔案搜尋優先序

  1. /etc/systemd/system/ - 管理員自訂,**優先級最高**
  2. /run/systemd/system/ - 運行時動態生成
  3. /usr/lib/systemd/system/ - 套件預設安裝,**優先級最低**

修改服務請 **cp 到 /etc/systemd/system/ 再編輯**,或使用 systemctl edit 服務名 建立 drop-in 片段。

systemctl 核心指令速查表

操作指令說明
啟動systemctl start 名稱.service.service 可省略
停止systemctl stop 名稱.service
重啟systemctl restart 名稱.servicestop + start
條件重啟systemctl try-restart 名稱.service僅運行中才重啟
重載配置systemctl reload 名稱.service不中斷服務,發送 SIGHUP
重載+條件重啟systemctl reload-or-restart 名稱.service支援 reload 則 reload,否則 restart
啟用開機自啟systemctl enable 名稱.service建立 WantedBy 連結
禁用開機自啟systemctl disable 名稱.service移除連結
查看狀態systemctl status 名稱.service含 PID、CGroup、最近日誌
檢查是否啟用systemctl is-enabled 名稱.service回傳 enabled/disabled/static
檢查是否運行systemctl is-active 名稱.service回傳 active/inactive/failed
列出所有服務systemctl list-units --type=service --all含非活動/失敗單元
列出可啟用服務systemctl list-unit-files --type=service顯示啟用狀態
查看單元檔內容systemctl cat 名稱.service合併顯示所有片段
編輯單元 (drop-in)systemctl edit 名稱.service建立 /etc/systemd/system/名稱.service.d/override.conf
完全編輯單元systemctl edit --full 名稱.service複製到 /etc/systemd/system/ 並編輯

服務狀態關鍵字解讀


● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2024-01-10 10:00:00 CST; 2h ago
     Docs: man:nginx(8)
  Process: 1234 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
  Process: 1235 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
 Main PID: 1236 (nginx)
    Tasks: 5 (limit: 4915)
   Memory: 15.2M
   CGroup: /system.slice/nginx.service
           ├─1236 nginx: master process /usr/sbin/nginx
           └─1237 nginx: worker process
  • Loaded:載入狀態、路徑、啟用狀態
  • Active:運行狀態 (active/running、active/exited、active/waiting、inactive、failed)
  • Main PID:主進程 ID
  • CGroup:控制群組層級,資源限制依此生效
  • Process:啟動/停止/重載過程的進程資訊

單元檔結構詳細解析


[Unit]
Description=服務描述
Documentation=man:xxx(8) 或 URL
After=network.target          # 排序依賴 (非強制要求)
Requires=network.target       # 強制依賴,失敗則本單元失敗
Wants=network.target          # 弱依賴,失敗不影響
Before=                       # 在指定單元前啟動
Conflicts=                    # 衝突單元,不可同時運行
ConditionPathExists=          # 條件啟動:路徑存在
ConditionKernelVersion=       # 條件啟動:核心版本

[Service]
Type=simple                   # simple/forking/oneshot/dbus/notify/idle
ExecStartPre=                 # 啟動前指令 (可多行)
ExecStart=                    # 主啟動指令 (必填)
ExecStartPost=                # 啟動後指令
ExecReload=                   # reload 指令
ExecStop=                     # 停止指令
ExecStopPost=                 # 停止後指令
Restart=no                    # no/on-success/on-failure/on-abnormal/on-watchdog/always
RestartSec=5                  # 重啟間隔
TimeoutStartSec=90            # 啟動超時
TimeoutStopSec=90             # 停止超時
User=www-data                 # 執行用戶
Group=www-data                # 執行群組
WorkingDirectory=/var/www     # 工作目錄
Environment=VAR=value         # 環境變數
EnvironmentFile=/etc/xxx.env  # 環境變數檔
LimitNOFILE=65535             # 檔案描述符限制
MemoryMax=1G                  # 記憶體限制 (cgroup v2)
CPUQuota=50%                  # CPU 配額
StandardOutput=journal        # 輸出導向
StandardError=journal

[Install]
WantedBy=multi-user.target    # 啟用時連結目標
Also=other.service            # 連帶啟用
Alias=alias.name              # 別名

進階除錯技巧

1. 查看完整日誌


journalctl -u nginx.service -f          # 即時追蹤
journalctl -u nginx.service --since "1 hour ago"
journalctl -u nginx.service -p err      # 只看錯誤級別
journalctl -u nginx.service -o verbose  # 完整欄位

2. 分析啟動失敗


systemctl status nginx.service -l       # -l 完整輸出不截斷
journalctl -u nginx.service -b -1       # 上一次開機的日誌
systemd-analyze verify nginx.service    # 語法檢查
systemd-analyze plot > boot.svg         # 啟動時間線圖

3. 進程資源限制驗證


systemctl show nginx.service --property=LimitNOFILE,MemoryMax,CPUQuota
cat /proc/$(systemctl show nginx.service --property=MainPID --value)/limits

4. 依賴關係圖


systemctl list-dependencies nginx.service
systemctl list-dependencies --reverse nginx.service  # 反向依賴
systemd-analyze dot | dot -Tpng > deps.png          # 圖形化 (需 graphviz)

從 SysV init 遷移對照表

SysV 指令Systemd 指令備註
service nginx startsystemctl start nginx相容保留
service nginx stopsystemctl stop nginx
service nginx restartsystemctl restart nginx
service nginx reloadsystemctl reload nginx
service nginx statussystemctl status nginxsystemd 輸出更豐富
chkconfig nginx onsystemctl enable nginx
chkconfig nginx offsystemctl disable nginx
chkconfig --listsystemctl list-unit-files --type=service
/etc/init.d/nginx/usr/lib/systemd/system/nginx.service單元檔取代腳本

最佳實踐

  • 使用 systemctl edit 建立 drop-in 覆蓋,避免修改原檔、升級覆蓋
  • 善用 Type=notify + sd_notify 實現精準啟動完成通知
  • 設定 Restart=on-failure + RestartSec=5 實現自愈
  • 配置 LimitNOFILE、MemoryMax 防止資源耗盡
  • 重要服務啟用 WatchdogSec 硬體/軟體看門狗
copyright © 萬盛學電腦網 all rights reserved