systemd およびサービス管理
26.10 バージョンの違い
26.10 は、systemd 261.3 を使用し、systemd-sysv-generator を削除します。カスタム /etc/init.d スクリプトは、生成されたサービスに依存できなくなりました。ネイティブの systemd ユニットに移行し、開始、停止、再起動、ブート アクティベーションをテストします。 公式リリースノート
systemd は、Ubuntu 26.04 の初期システムおよびサービス マネージャーであり、システムのブートストラップ、サービスおよびデーモンの管理を担当します。 systemd をマスターすることは、Ubuntu システム管理にとって不可欠なスキルです。
systemctlの基本
サービス状態の管理
# Start a service
sudo systemctl start nginx
# Stop a service
sudo systemctl stop nginx
# Restart a service
sudo systemctl restart nginx
# Reload configuration (without interrupting the service)
sudo systemctl reload nginx
# Reload if supported, otherwise restart
sudo systemctl reload-or-restart nginx
# Check service status
systemctl status nginxブートサービス管理
# Enable a service at boot
sudo systemctl enable nginx
# Disable a service at boot
sudo systemctl disable nginx
# Enable and start immediately
sudo systemctl enable --now nginx
# Prevent a service from being started (including manually)
sudo systemctl mask nginx
# Remove the mask
sudo systemctl unmask nginxサービス情報を見る
# List all running services
systemctl list-units --type=service --state=running
# List all installed services
systemctl list-unit-files --type=service
# List failed services
systemctl list-units --failed
# View a service's dependencies
systemctl list-dependencies nginx
# View detailed service properties
systemctl show nginx
# Check if a service is active
systemctl is-active nginx
# Check if a service is enabled at boot
systemctl is-enabled nginxサービスユニットファイル
ユニットファイルの場所
systemd サービス ユニット ファイルは、優先順位 (最高から最低) の順に次の場所に保存されます。
| パス | 説明 |
|---|---|
/etc/systemd/system/ | カスタム管理構成、最高の優先度 |
/run/systemd/system/ | ランタイム生成のユニット ファイル |
/lib/systemd/system/ | パッケージによってインストールされるデフォルトのユニット ファイル |
ユニットファイルの表示
# View a service's unit file contents
systemctl cat nginx.service
# View the unit file path
systemctl show -p FragmentPath nginx.service
# Edit a unit file (creates an override)
sudo systemctl edit nginx.service
# Edit the full unit file
sudo systemctl edit --full nginx.serviceユニットファイルの構造
一般的なサービス ユニット ファイルには、次の 3 つのセクションがあります。
[Unit]
Description=Service description
Documentation=https://example.com/docs
After=network.target
Wants=network-online.target
Requires=postgresql.service
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/opt/myapp
ExecStartPre=/opt/myapp/pre-start.sh
ExecStart=/opt/myapp/start.sh
ExecStop=/opt/myapp/stop.sh
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
Environment=NODE_ENV=production
EnvironmentFile=/opt/myapp/.env
[Install]
WantedBy=multi-user.target共通サービスの種類
| タイプ | 説明 |
|---|---|
simple | デフォルト; ExecStart によって開始されたプロセスがメインプロセスです |
forking | サービスは子プロセスをフォークします。親が終了すると起動は完了したとみなされます |
oneshot | 1 回限りのタスク。プロセスが終了すると完了したとみなされます |
notify | サービスは、起動が完了すると sd_notify 経由で systemd に通知します。 |
idle | シンプルに似ていますが、他のタスクが完了するのを待ってから開始します。 |
再起動ポリシー
| オプション | 説明 |
|---|---|
no | 自動的に再起動しない (デフォルト) |
on-success | 通常終了時に再起動する |
on-failure | 異常終了時に再起動する |
on-abnormal | シグナルまたはタイムアウトによって強制終了された場合に再起動する |
on-abort | キャッチされなかった信号によって強制終了された場合に再起動する |
always | 終了理由に関係なく常に再起動します |
カスタムサービスの作成
例: Node.js アプリケーション サービス
ユニットファイルを作成します。
sudo nano /etc/systemd/system/myapp.service次のコンテンツを追加します。
[Unit]
Description=My Node.js Application
After=network.target
[Service]
Type=simple
User=nodeapp
Group=nodeapp
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp
Environment=NODE_ENV=production PORT=3000
# Security hardening
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/opt/myapp/data
PrivateTmp=yes
[Install]
WantedBy=multi-user.targetサービスを有効にして開始します。
# Reload systemd configuration
sudo systemctl daemon-reload
# Start the service
sudo systemctl enable --now myapp.service
# Check status
systemctl status myapp.service
# View logs
journalctl -u myapp.service -f例: Python アプリケーション サービス
[Unit]
Description=Python Flask Application
After=network.target
[Service]
Type=simple
User=flask
Group=flask
WorkingDirectory=/opt/flask-app
ExecStart=/opt/flask-app/venv/bin/gunicorn -w 4 -b 0.0.0.0:8000 app:app
Restart=always
RestartSec=5
Environment=FLASK_ENV=production
[Install]
WantedBy=multi-user.target例: ウォッチドッグを使用したサービス
[Unit]
Description=Critical Service with Watchdog
After=network.target
[Service]
Type=notify
ExecStart=/opt/critical/run.sh
WatchdogSec=30
Restart=on-failure
RestartSec=5
# Auto-restart on failure, up to 5 attempts
StartLimitIntervalSec=300
StartLimitBurst=5
[Install]
WantedBy=multi-user.targetオーバーライドを使用して既存のサービスを変更する
/lib/systemd/system/ 内のファイルを直接変更することはお勧めできません。代わりに、オーバーライドを使用してください。
# Create an override file
sudo systemctl edit nginx.serviceこれにより、設定のオーバーライドを追加できるエディターが開きます。
[Service]
# Add memory limit
MemoryMax=512M
# Change restart policy
Restart=always
RestartSec=3オーバーライド ファイルは /etc/systemd/system/nginx.service.d/override.conf に保存されます。
# View the merged full configuration
systemctl cat nginx.service
# Reload configuration
sudo systemctl daemon-reload
sudo systemctl restart nginxシステム管理コマンド
# View boot time
systemd-analyze
# View boot time per service (sorted)
systemd-analyze blame
# View the boot critical chain
systemd-analyze critical-chain
# View the current default target
systemctl get-default
# Set the default target
sudo systemctl set-default multi-user.target # Command-line mode
sudo systemctl set-default graphical.target # Graphical mode
# Shutdown and reboot
sudo systemctl poweroff
sudo systemctl reboot
# Suspend and hibernate
sudo systemctl suspend
sudo systemctl hibernateリソース制限
サービスユニットファイルでリソース制限を設定できます。
[Service]
# CPU limit
CPUQuota=50%
# Memory limit
MemoryMax=1G
MemoryHigh=800M
# I/O limit
IOWeight=100
IOReadBandwidthMax=/dev/sda 10M
# Process count limit
TasksMax=100
# File descriptor limit
LimitNOFILE=65535トラブルシューティング
# View the reason a service failed
systemctl status myapp.service
journalctl -u myapp.service --no-pager -n 50
# Validate unit file syntax
systemd-analyze verify /etc/systemd/system/myapp.service
# View systemd's own logs
journalctl -b _PID=1
# Reset the failure count
sudo systemctl reset-failed myapp.service関連記事
- journalctl Log Queries —journalctl を使用して systemd サービス ログを表示およびフィルタリングする
- スケジュールされたタスク (cron) — cron タイマーと systemd タイマーを使用した定期的なスケジュールされたタスクの設定