systemd

Linux init system と サービスマネージャ

systemdとは

systemdは、Linux のシステムとサービスを管理するマネージャです。 従来のSysV initを置き換え、並列起動、依存関係管理、cgroups統合などを提供します。

ユニットファイル

ユニットファイルはサービスの定義ファイル。 INIファイル形式で記述します。

/etc/systemd/system/

管理者が作成するユニット(優先度高)

/usr/lib/systemd/system/

パッケージがインストールするユニット

/run/systemd/system/

ランタイム生成ユニット

1# /etc/systemd/system/myapp.service
2[Unit]
3Description=My Application
4After=network.target
5Wants=network-online.target
6
7[Service]
8Type=simple
9User=myapp
10Group=myapp
11WorkingDirectory=/opt/myapp
12ExecStart=/opt/myapp/bin/myapp
13ExecReload=/bin/kill -HUP $MAINPID
14Restart=always
15RestartSec=10
16
17# リソース制限
18MemoryLimit=512M
19CPUQuota=50%
20
21# セキュリティ
22NoNewPrivileges=true
23PrivateTmp=true
24
25[Install]
26WantedBy=multi-user.target

ユニットファイルの構造

[Unit] セクション

  • Description: 説明
  • After: このユニットの後に起動
  • Before: このユニットの前に起動
  • Wants: 弱い依存関係
  • Requires: 強い依存関係

[Service] セクション

  • Type: simple, forking, oneshot, notify
  • ExecStart: 起動コマンド
  • ExecStop: 停止コマンド
  • ExecReload: リロードコマンド
  • Restart: no, always, on-failure
  • RestartSec: 再起動間隔

[Install] セクション

  • WantedBy: enableで有効化されるターゲット
  • RequiredBy: 必須で有効化されるターゲット
  • Alias: 別名

サービスタイプ

simple

プロセスがフォアグラウンドで実行。デフォルト。

forking

デーモン化してバックグラウンドに移行。PIDファイル指定推奨。

oneshot

一度実行して終了。RemainAfterExit=trueと組み合わせ。

notify

サービスがsd_notify()で起動完了を通知。

タイマー(cron代替)

1# /etc/systemd/system/backup.timer
2[Unit]
3Description=Daily Backup Timer
4
5[Timer]
6OnCalendar=daily
7# または OnCalendar=*-*-* 02:00:00
8Persistent=true
9
10[Install]
11WantedBy=timers.target
12
13# /etc/systemd/system/backup.service
14[Unit]
15Description=Backup Service
16
17[Service]
18Type=oneshot
19ExecStart=/opt/scripts/backup.sh
1# タイマー操作
2systemctl enable backup.timer
3systemctl start backup.timer
4systemctl list-timers

管理コマンド

1# ユニットファイル変更後
2systemctl daemon-reload
3
4# 依存関係確認
5systemctl list-dependencies nginx
6systemctl list-dependencies --reverse nginx
7
8# 失敗したサービス
9systemctl --failed
10
11# リソース使用状況
12systemd-cgtop
13
14# ブート分析
15systemd-analyze
16systemd-analyze blame
17systemd-analyze critical-chain
18
19# ユニットファイル確認
20systemctl cat nginx.service
21systemctl show nginx.service

SRE/インフラ観点

ベストプラクティス

  • Restart=alwaysRestartSecで自動復旧
  • MemoryLimit/CPUQuotaでリソース制限
  • PrivateTmp=trueでセキュリティ強化
  • After=network-online.targetでネットワーク依存を明示

トラブルシューティング

  • • 起動失敗: journalctl -u service -xe
  • • 設定確認: systemctl show service
  • • 起動順序: systemd-analyze critical-chain