プロセス管理

Linux systemctlコマンド入門|サービスとユニットを管理する

Linux systemctl サービス管理

Linux systemctlコマンド入門
サービスとユニットを管理する

systemctlは、Linuxのサービス(デーモン)を管理するためのコマンドです。Webサーバーやデータベースなどの起動・停止・自動起動設定を行えます。

こんな人向けの記事です

  • Linuxサーバーでサービスの管理方法を学びたい人
  • Nginx・MySQL等のサービスを起動・停止したい人
  • OS起動時の自動起動設定を行いたい人

Step 1systemctlの基本操作

サービスの起動・停止・再起動は以下のコマンドで行います。

ターミナル
# サービスを起動
sudo systemctl start nginx

# サービスを停止
sudo systemctl stop nginx

# サービスを再起動
sudo systemctl restart nginx

# 設定ファイルの再読み込み(サービスは停止しない)
sudo systemctl reload nginx
restart vs reload
  • restart:サービスを一度停止してから起動し直す(一瞬ダウンタイムあり)
  • reload:サービスを動かしたまま設定ファイルだけ再読み込み(ダウンタイムなし)

Step 2サービスの状態確認

status サブコマンドでサービスの詳細な状態を確認できます。

ターミナル
# サービスの状態を確認
systemctl status nginx

# 動いているかどうかだけ確認
systemctl is-active nginx

# 自動起動が有効かどうか確認
systemctl is-enabled nginx

status の出力には、Active状態(active/inactive/failed)、PID、メモリ使用量、最近のログなどが表示されます。

Step 3自動起動の設定

OS起動時にサービスを自動で起動させるには enable を使います。

ターミナル
# 自動起動を有効にする
sudo systemctl enable nginx

# 自動起動を有効にして、今すぐ起動もする
sudo systemctl enable --now nginx

# 自動起動を無効にする
sudo systemctl disable nginx
enable だけでは起動しない

enable は次回のOS起動時から有効になります。今すぐ起動もしたい場合は enable --now または別途 start を実行してください。

Step 4サービス一覧の確認

システム上のサービス一覧を確認できます。

ターミナル
# 全ユニットの一覧
systemctl list-units

# サービスのみ表示
systemctl list-units --type=service

# 実行中のサービスのみ
systemctl list-units --type=service --state=running

# 自動起動が有効なサービス一覧
systemctl list-unit-files --type=service --state=enabled

Step 5ログの確認

サービスのログは journalctl コマンドで確認します。

ターミナル
# 特定サービスのログを確認
journalctl -u nginx

# 最新のログだけ表示
journalctl -u nginx -n 50

# リアルタイムでログを追跡
journalctl -u nginx -f

# 今日のログだけ表示
journalctl -u nginx --since today

Step 6実践的な活用例

日常的なサーバー管理でよく使うパターンです。

ターミナル
# Webサーバーのセットアップ
sudo systemctl enable --now nginx
sudo systemctl status nginx

# サービスが失敗した時の確認
systemctl --failed
journalctl -u nginx --since "1 hour ago"

# 設定ファイル変更後の安全な反映
sudo nginx -t              # 設定テスト
sudo systemctl reload nginx # OKなら反映

# システム全体の状態確認
systemctl list-units --type=service --state=running
設定テストを忘れずに

NginxやApacheなどの設定ファイルを変更した後は、必ず設定テスト(nginx -tapachectl configtest)を実行してからreloadしましょう。構文エラーがあるとサービスが停止してしまいます。