Linux-systemctl 基本指令與使用

目錄

展開

腳本內容

service

[Unit]
Description=svc                 #簡短描述這個服務的用途。
After=network.target            #指定這個服務要在某些其他服務之後啟動 ex:network.target
Requires=getsqu.service         #指定必須同時啟動的 unit,缺少就會失敗。
Conflicts=apache2.service       #指定互斥的 unit,不能同時啟動。(這個範例就是假設nginx跟apache互斥,不能同時啟動)
[Service]
Type=oneshot                    #指定服務的型態
ExecStart=/path                 #啟動服務時要執行的指令
ExecReload=/path                #定義重新載入服務時要執行的指令(例如重新讀取設定檔)。
ExecStop=shutdown -r            #定義停止服務時要執行的指令。
EnvironmentFile=/path/          #指定環境變數檔案路徑
Restart=always                  #定義服務失敗後是否自動重啟
RestartSec=3                    #重啟前等待的秒數


[Install]                       #定義這個 unit 要如何被啟用
WantedBy=    

常用的type

Type 值 說明 適用情境
simple 預設值。直接執行 ExecStart,systemd 視程式啟動後就算服務已啟動。 大部分前景執行的程式,例如 Python、Node.js、Go 等應用程式。
forking 適合會在啟動時 fork 成背景程序的程式。systemd 會認為父程序結束後,子程序就是服務。 傳統的 daemon 程式,例如 httpdmysqld
oneshot 執行一次就結束,不會常駐。常用於初始化或設定任務。 執行資料庫 migration、設定網路參數、啟動前置腳本。
notify 程式會透過 systemd 的通知機制告知「已啟動完成」。 需要精確控制啟動完成時機的服務,例如 systemd-networkd
idle 延遲到系統空閒時才執行。 非必要的背景工作,避免影響主要服務啟動。

常用的target

Target 說明
basic.target 基本系統初始化完成。
multi-user.target 多使用者文字模式,伺服器常用。
graphical.target 圖形介面模式(相當於 runlevel 5)。
timers.target 管理所有定時器。
network.target 網路啟動完成。
default.target 系統預設進入的 target(通常是 multi-user 或 graphical)。

path

[Unit]                     #同上
Description=svc.path
[Path]
Unit=unit.service          #指定觸發的Unit  
PathChanged=/path          #監看的資料夾
[Install]
WantedBy=multi-user.target #multi-user.target 是 systemd 代表系統進入「多使用者模式」時的狀態(代表開機完成的差不多了,可以開始啟用服務)

timer

[Unit]
Description=svc-timer

[Timer]
OnCalendar=*-*-* 03:00:00  #觸發時間,範例為每天三點
Persistent=true            #如果當下為關機,開機自動補執行

[Install]
WantedBy=timers.target     #timers.target 是 systemd 專門用來管理所有 timer 的 target

常用指令

指令 說明 範例
systemctlstart <unit> 立即啟動服務(不會改變開機自動啟動設定)。 systemctlstart nginx.service
systemctlstop <unit> 停止服務。 systemctlstop nginx.service
systemctlrestart <unit> 重啟服務(先停再啟)。 systemctlrestart nginx.service
systemctlreload <unit> 重新載入設定檔(服務需支援 reload)。 systemctlreload nginx.service
systemctlenable <unit> 設定服務開機自動啟動。 systemctlenable nginx.service
systemctldisable <unit> 取消服務開機自動啟動。 systemctldisable nginx.service
systemctlstatus <unit> 查看服務狀態與 log 摘要。 systemctlstatus nginx.service
systemctlis-enabled <unit> 檢查服務是否設定為開機自動啟動。 systemctlis-enabled nginx.service
systemctllist-units --type=service 列出目前所有服務的狀態。 systemctllist-units --type=service
journalctl-u <unit> 查看指定服務的完整 log。 journalctl-u nginx.service
systemctl daemon-reload 重新載入 systemd 設定(修改 unit 檔後要執行)。 systemctldaemon-reload