Systemd 單元範本與實例化核心概念
單元範本檔案命名慣例:名稱@.service (如 getty@.service)。實例化時以 @ 區隔:**範本名@實例名.service** (如 getty@tty1.service)。
實例化觸發方式
- 相依關係自動實例化:在另一單元的
Wants= 或 Requires= 列出實例名
- 手動啟動:
systemctl start 範本名@實例名.service
- 啟用開機自啟:
systemctl enable 範本名@實例名.service
單元說明符 (Specifiers) - 實例化動態替換
| 說明符 | 含義 | 範例 (getty@tty1.service) |
%n | 完整單元名稱 (含副檔名) | getty@tty1.service |
%N | %n 轉義後 (不可列印字元替換) | getty@tty1.service |
%p | 前綴名稱 (@ 前) | getty |
%i | 實例名稱 (@ 到 .service 之間) | tty1 |
%I | %i 轉義後 | tty1 |
%H | 主機名稱 | myserver |
%t | 運行時目錄 (root:/run, user:$XDG_RUNTIME_DIR) | /run |
%u | 使用者 UID | 1000 |
%U | 使用者名稱 | admin |
經典範例:getty@.service
# /usr/lib/systemd/system/getty@.service
[Unit]
Description=Getty on %I
Documentation=man:agetty(8) man:systemd-getty-generator(8)
After=systemd-user-sessions.service plymouth-quit-wait.service
After=rc-local.service
[Service]
ExecStart=-/sbin/agetty -o '-p -- \\u' --noclear %I $TERM
Type=idle
Restart=always
RestartSec=0
UtmpIdentifier=%I
TTYPath=/dev/%I
TTYReset=yes
TTYVHangup=yes
KillMode=process
IgnoreSIGPIPE=no
SendSIGHUP=yes
[Install]
WantedBy=getty.target
實例化效果
systemctl start getty@tty1.service → Description=Getty on tty1、ExecStart=... /dev/tty1
systemctl start getty@ttyS0.service → Description=Getty on ttyS0、ExecStart=... /dev/ttyS0
實戰:建立自訂多實例服務
場景:為每個客戶運行獨立的應用實例
1. 建立範本檔案
# /etc/systemd/system/myapp@.service
[Unit]
Description=MyApp Instance %i
After=network.target
[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp/instances/%i
ExecStart=/opt/myapp/bin/myapp --config /opt/myapp/instances/%i/config.yaml
Restart=on-failure
RestartSec=5
Environment=INSTANCE_NAME=%i
[Install]
WantedBy=multi-user.target
2. 建立實例配置目錄結構
mkdir -p /opt/myapp/instances/{customer-a,customer-b,customer-c}
# 每目錄放置獨立 config.yaml
3. 管理實例
# 啟動特定實例
systemctl start myapp@customer-a
# 啟用開機自啟
systemctl enable myapp@customer-b
# 查看所有實例狀態
systemctl status 'myapp@*'
# 批次操作
systemctl start 'myapp@customer-*'
# 查看實例日誌
journalctl -u myapp@customer-a -f
進階技巧
1. 產生器 自動建立實例
# /usr/lib/systemd/system-generators/myapp-generator
#!/bin/bash
# 開機時自動為 /opt/myapp/instances/* 建立 Wants 連結
for dir in /opt/myapp/instances/*/; do
instance=$(basename "$dir")
ln -sf /etc/systemd/system/myapp@.service "$1/myapp@$instance.service"
done
2. 即時模板參數覆蓋 (systemd-run)
# 臨時覆蓋參數啟動
systemd-run --unit=myapp@temp --setenv=DEBUG=1 --property=MemoryMax=512M /opt/myapp/bin/myapp
3. 實例化 Socket 啟動
# myapp@.socket
[Socket]
ListenStream=/run/myapp-%i.sock
Accept=yes
[Install]
WantedBy=sockets.target
常見錯誤與除錯
| 錯誤 | 原因 | 解決 |
| Failed to start getty@.service (template) | 直接啟動範本而非實例 | 必須指定實例名:getty@tty1.service |
| Unit not found | 實例名拼寫錯誤或範本不存在 | systemctl list-unit-files 'name@*' 查看可用 |
| 說明符未替換 | 用在不支援的欄位 (如 [Install] WantedBy) | 僅支援 [Unit]/[Service]/[Socket] 等執行階段欄位 |
| 多實例衝突 | 共用同一 PID 檔/連接埠 | 使用 %i 區隔:PIDFile=/run/%i.pid, ListenPort=8000+%i |