systemd チートブック
systemctl
ユニットタイプが service の場合は .serviceを省略できる
サービス一覧の表示
$ systemctl
$ systemctl list-units
$ systemctl list-units [ユニット名]
$ systemctl list-unit-files --type=service
$ systemctl list-unit-files --type=service [ユニット名]
ワイルドカードも使える
$ systemctl list-units ss*
$ systemctl list-unit-files --type=service ss*
起動・停止
操作 | コマンド |
---|---|
サービス起動 | systemctl start [ユニット名] |
サービス停止 | systemctl stop [ユニット名] |
サービス再起動 | systemctl restart [ユニット名] |
サービスステータス表示 | systemctl status [ユニット名] |
サービスリロード | systemctl reload [ユニット名] |
自動起動
操作 | コマンド |
---|---|
サービス自動起動有効 | systemctl enable [ユニット名] |
サービス自動起動無効 | systemctl disable [ユニット名] |
サービス自動起動デフォルト | systemctl preset [ユニット名] |
サービス自動起動設定確認 | systemctl is-enabled [ユニット名] |
設定ファイルの再読込
systemctl daemon-reload
journalctl
操作 | コマンド |
---|---|
ユニット名のログ取得 | journalctl -u [ユニット名] |
tail -f 的動作 | journalctl -u [ユニット名] -f |
カーネルログ取得 | journalctl -k |
ファイルに書き出し | journalctl -o |
永続化するためには /etc/systemd/journald.conf を編集する。
サービスの作成
プログラム
$ sudo sh -c 'cat > /opt/hello.sh' << 'EOS'
#!/bin/bash
set -eu
while true; do
echo "PID:$(echo $$), DATE:$(date +'%Y-%m-%d %H:%M:%S')"
sleep 5
done
EOS
$ sudo chmod 755 /opt/hello.sh
/opt/hello.sh
(CTRL+C)
設定ファイル
$ sudo sh -c 'cat > /etc/systemd/system/hello.service' << 'EOS'
[Unit]
Description = hello daemon
[Service]
ExecStart = /opt/hello.sh
Restart = always
Type = simple
[Install]
WantedBy = multi-user.target
EOS
確認
$ systemctl list-unit-files --type=service | grep hello
hello.service disabled
有効化(自動起動)
$ sudo systemctl enable hello
起動
$ sudo systemctl start hello
確認
$ systemctl status hello
* hello.service - hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2018-09-24 16:52:34 JST; 23s ago
Main PID: 1253 (hello.sh)
CGroup: /system.slice/hello.service
|-1253 /bin/bash /opt/hello.sh
`-1271 sleep 5
....
ログ
$ journalctl -u hello
停止
$ sudo systemctl stop hello
無効化
$ sudo systemctl disable hello
service設定例
ネットワークが有効になりPINGが成功するまで繰り返し、成功したら静的ルーティングを設定する
sudo bash -xe << 'END_OF_SNIPPETS'
NAME=static-routing
systemctl stop $NAME || true
systemctl disable $NAME || true
# -- ここから
cat > /etc/systemd/system/$NAME.service << 'EOS'
[Unit]
Description = static routing
Wants=network-online.target
After=network-online.target
[Service]
ExecStartPre = /bin/sh -c 'until ping -c 1 gw2.homenetwork; do sleep 1; done'
ExecStart = /sbin/route add -net 192.168.5.0/24 gw gw2.homenetwork
Type = oneshot
[Install]
WantedBy = multi-user.target
EOS
# -- ここまで
systemctl daemon-reload
systemctl enable $NAME
systemctl start $NAME
sleep 5
systemctl status $NAME
END_OF_SNIPPETS