systemd
Linuxのサービス管理システムであるsystemdについて学びます。
目次
systemdとは
systemdの概要
┌─────────────────────────────────────────────────────────────┐
│ systemd の構成 │
├─────────────────────────────────────────────────────────────┤
│ │
│ カーネル起動 │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ systemd (PID 1) │ │
│ │ │ │
│ │ ・サービス管理 (起動、停止、再起動) │ │
│ │ ・依存関係の解決 │ │
│ │ ・並列起動による高速ブート │ │
│ │ ・ログ管理 (journald) │ │
│ │ ・ソケットアクティベーション │ │
│ │ ・タイマー (cron代替) │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────┐ ┌────────┐ ┌────────┐ │
│ │ nginx │ │ sshd │ │postgres│ │
│ │.service│ │.service│ │.service│ │
│ └────────┘ └────────┘ └────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
従来のinitシステムとの比較
| 特徴 | SysVinit | systemd |
|---|---|---|
| 起動方式 | シーケンシャル | 並列 |
| 設定 | シェルスクリプト | Unitファイル |
| 依存関係 | 手動管理 | 自動解決 |
| ログ | 分散 | 統合(journald) |
| ソケット | 手動 | アクティベーション |
systemctlコマンド
サービスの操作
# サービスの状態確認
systemctl status nginx
systemctl status nginx.service
# サービスの起動・停止・再起動
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # 設定再読み込み(プロセス継続)
# 自動起動の有効化・無効化
sudo systemctl enable nginx # 起動時に自動起動
sudo systemctl disable nginx # 自動起動を無効化
sudo systemctl enable --now nginx # 有効化と起動を同時に
# サービスが有効か確認
systemctl is-enabled nginx
systemctl is-active nginx
サービス一覧
# すべてのサービス
systemctl list-units --type=service
# 実行中のサービスのみ
systemctl list-units --type=service --state=running
# 失敗したサービス
systemctl list-units --type=service --state=failed
# 有効なサービス(自動起動)
systemctl list-unit-files --type=service --state=enabled
依存関係の確認
# 依存しているUnit
systemctl list-dependencies nginx
# 逆依存(このUnitに依存しているもの)
systemctl list-dependencies nginx --reverse
# ツリー表示
systemctl list-dependencies --all nginx
システム全体の操作
# システム再起動
sudo systemctl reboot
# シャットダウン
sudo systemctl poweroff
# サービスのデーモン再読み込み
sudo systemctl daemon-reload
# 全体の状態確認
systemctl status
Unitファイル
Unitの種類
| 種類 |
|---|