systemd and Service Management

Level: Beginner Module: Linux Fundamentals 6 min read Lesson 5 of 10

Overview

  • What you’ll learn: How to manage system services using systemd, create custom unit files, and analyze logs with journalctl.
  • Prerequisites: Lesson 4 – Process Management and Signals
  • Estimated reading time: 17 minutes

Introduction

systemd is the init system and service manager used by Ubuntu and most modern Linux distributions. It is the first process started by the kernel (PID 1) and is responsible for bootstrapping the entire user space, managing services, and handling system state transitions such as startup, shutdown, and reboot.

As a system administrator, you will interact with systemd daily through systemctl to start and stop services, journalctl to read logs, and unit files to define how services behave. This lesson covers all three in depth.

systemd Architecture

systemd organizes the system into units. A unit is a resource that systemd knows how to manage. The most common unit types are:

  • .service — A daemon or process (e.g., nginx.service, ssh.service).
  • .timer — A scheduled task (replacement for cron in some cases).
  • .socket — A network or IPC socket for socket-based activation.
  • .target — A group of units representing a system state (e.g., multi-user.target).
  • .mount — A filesystem mount point.
  • .path — A filesystem path monitor.
$ systemctl list-units --type=service --state=running | head -10
UNIT                        LOAD   ACTIVE SUB     DESCRIPTION
cron.service                loaded active running Regular background program processing
dbus.service                loaded active running D-Bus System Message Bus
networkd-dispatcher.service loaded active running Dispatcher daemon for systemd-networkd
ssh.service                 loaded active running OpenBSD Secure Shell server
systemd-journald.service    loaded active running Journal Service
systemd-resolved.service    loaded active running Network Name Resolution

Managing Services with systemctl

The systemctl command is your primary tool for interacting with systemd:

$ sudo systemctl start nginx          # Start a service
$ sudo systemctl stop nginx           # Stop a service
$ sudo systemctl restart nginx        # Restart a service
$ sudo systemctl reload nginx         # Reload configuration without restart
$ sudo systemctl status nginx         # View service status

$ sudo systemctl enable nginx         # Start automatically at boot
$ sudo systemctl disable nginx        # Do not start at boot
$ sudo systemctl is-enabled nginx     # Check if enabled
enabled

$ sudo systemctl is-active nginx      # Check if currently running
active

Service Status Output

$ systemctl status ssh
● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2024-01-15 08:00:00 UTC; 6h ago
       Docs: man:sshd(8)
   Main PID: 789 (sshd)
      Tasks: 1 (limit: 4657)
     Memory: 5.2M
        CPU: 234ms
     CGroup: /system.slice/ssh.service
             └─789 "sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups"

Jan 15 08:00:00 server systemd[1]: Started OpenBSD Secure Shell server.

Unit Files

Unit files define how systemd manages a service. System unit files are stored in /lib/systemd/system/, while custom or override files go in /etc/systemd/system/.

$ cat /lib/systemd/system/ssh.service
[Unit]
Description=OpenBSD Secure Shell server
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run

[Service]
EnvironmentFile=-/etc/default/ssh
ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartPreventExitStatus=255
Type=notify

[Install]
WantedBy=multi-user.target

Creating a Custom Service

$ sudo nano /etc/systemd/system/myapp.service
[Unit]
Description=My Custom Application
After=network.target

[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/run.sh
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

$ sudo systemctl daemon-reload        # Reload unit file definitions
$ sudo systemctl enable --now myapp   # Enable and start immediately

Logging with journalctl

systemd collects all logs through its journal. The journalctl command lets you query these logs:

$ journalctl                          # All logs
$ journalctl -u ssh                   # Logs for ssh service only
$ journalctl -u nginx --since "1 hour ago"
$ journalctl -u nginx --since "2024-01-15" --until "2024-01-16"
$ journalctl -f                       # Follow new log entries (like tail -f)
$ journalctl -p err                   # Only error-level and above
$ journalctl -b                       # Logs since last boot
$ journalctl -b -1                    # Logs from previous boot
$ journalctl --disk-usage             # Check journal disk usage
Archived and active journals take up 48.0M in the file system.

Targets

Targets group units together to represent system states (similar to SysV runlevels):

$ systemctl get-default
multi-user.target

$ sudo systemctl set-default graphical.target   # Set GUI as default
$ sudo systemctl isolate rescue.target          # Switch to rescue mode

# Common targets:
# multi-user.target  — Normal multi-user system (no GUI), like runlevel 3
# graphical.target   — Multi-user with GUI, like runlevel 5
# rescue.target      — Single-user rescue mode
# emergency.target   — Emergency shell

Key Takeaways

  • systemd is the init system on modern Ubuntu; it manages services, sockets, timers, and more through unit files.
  • Use systemctl start|stop|restart|status|enable|disable to manage services.
  • Unit files have three sections: [Unit] for dependencies, [Service] for execution, [Install] for boot integration.
  • journalctl provides powerful log querying — filter by service, time range, priority, or boot.
  • Targets group units into system states; multi-user.target is the default for servers.

What’s Next

In Lesson 6, you will learn about Package Management with APT — how to install, update, and manage software packages on Ubuntu.

繁體中文

概述

  • 學習目標:學習如何使用 systemd 管理系統服務、建立自訂單元檔案,以及使用 journalctl 分析日誌。
  • 先決條件:第 4 課 – 行程管理和信號
  • 預計閱讀時間:17 分鐘

簡介

systemd 是 Ubuntu 和大多數現代 Linux 發行版使用的初始化系統和服務管理器。它是核心啟動的第一個行程(PID 1),負責引導整個使用者空間、管理服務以及處理系統狀態轉換。

systemd 架構

systemd 將系統組織成單元。單元是 systemd 知道如何管理的資源。最常見的單元類型包括:

  • .service — 守護行程或行程。
  • .timer — 排程任務。
  • .socket — 用於基於套接字啟動的網路或 IPC 套接字。
  • .target — 代表系統狀態的單元群組。

使用 systemctl 管理服務

$ sudo systemctl start nginx          # 啟動服務
$ sudo systemctl stop nginx           # 停止服務
$ sudo systemctl restart nginx        # 重新啟動服務
$ sudo systemctl status nginx         # 檢視服務狀態
$ sudo systemctl enable nginx         # 開機自動啟動
$ sudo systemctl disable nginx        # 不在開機時啟動

單元檔案

單元檔案定義了 systemd 如何管理服務。系統單元檔案儲存在 /lib/systemd/system/,自訂檔案放在 /etc/systemd/system/

建立自訂服務

[Unit]
Description=My Custom Application
After=network.target

[Service]
Type=simple
User=appuser
ExecStart=/opt/myapp/run.sh
Restart=always

[Install]
WantedBy=multi-user.target

$ sudo systemctl daemon-reload        # 重新載入單元檔案定義
$ sudo systemctl enable --now myapp   # 啟用並立即啟動

使用 journalctl 查看日誌

$ journalctl -u ssh                   # 僅 ssh 服務的日誌
$ journalctl -u nginx --since "1 hour ago"
$ journalctl -f                       # 即時跟蹤新日誌
$ journalctl -p err                   # 僅錯誤等級及以上
$ journalctl -b                       # 自上次開機以來的日誌

目標

目標將單元群組在一起以代表系統狀態:

  • multi-user.target — 正常的多使用者系統(無圖形介面)。
  • graphical.target — 帶圖形介面的多使用者系統。
  • rescue.target — 單使用者救援模式。

重點摘要

  • systemd 是現代 Ubuntu 上的初始化系統;透過單元檔案管理服務、套接字、計時器等。
  • 使用 systemctl start|stop|restart|status|enable|disable 管理服務。
  • 單元檔案有三個區段:[Unit] 用於相依性、[Service] 用於執行、[Install] 用於開機整合。
  • journalctl 提供強大的日誌查詢功能。
  • 目標將單元群組為系統狀態;multi-user.target 是伺服器的預設值。

下一步

在第 6 課中,您將學習使用 APT 的套件管理——如何在 Ubuntu 上安裝、更新和管理軟體套件。

日本語

概要

  • 学習内容:systemd を使用したシステムサービスの管理、カスタムユニットファイルの作成、journalctl によるログ分析。
  • 前提条件:レッスン4 – プロセス管理とシグナル
  • 推定読了時間:17分

はじめに

systemd は Ubuntu とほとんどの最新 Linux ディストリビューションで使用されている init システムおよびサービスマネージャーです。カーネルが最初に起動するプロセス(PID 1)であり、ユーザー空間全体のブートストラップ、サービスの管理、システム状態の遷移を担当します。

systemd アーキテクチャ

systemd はシステムをユニットに整理します。最も一般的なユニットタイプは:

  • .service — デーモンまたはプロセス。
  • .timer — スケジュールされたタスク。
  • .socket — ソケットベースのアクティベーション用ソケット。
  • .target — システム状態を表すユニットのグループ。

systemctl でサービスを管理

$ sudo systemctl start nginx          # サービスを開始
$ sudo systemctl stop nginx           # サービスを停止
$ sudo systemctl restart nginx        # サービスを再起動
$ sudo systemctl status nginx         # サービスの状態を表示
$ sudo systemctl enable nginx         # ブート時に自動起動
$ sudo systemctl disable nginx        # ブート時に起動しない

ユニットファイル

ユニットファイルは systemd がサービスをどのように管理するかを定義します。システムユニットファイルは /lib/systemd/system/ に、カスタムファイルは /etc/systemd/system/ に配置します。

カスタムサービスの作成

[Unit]
Description=My Custom Application
After=network.target

[Service]
Type=simple
User=appuser
ExecStart=/opt/myapp/run.sh
Restart=always

[Install]
WantedBy=multi-user.target

$ sudo systemctl daemon-reload        # ユニットファイル定義を再読み込み
$ sudo systemctl enable --now myapp   # 有効化して即座に起動

journalctl でログを確認

$ journalctl -u ssh                   # ssh サービスのログのみ
$ journalctl -u nginx --since "1 hour ago"
$ journalctl -f                       # 新しいログエントリをリアルタイムで追跡
$ journalctl -p err                   # エラーレベル以上のみ
$ journalctl -b                       # 最後のブートからのログ

ターゲット

  • multi-user.target — 通常のマルチユーザーシステム(GUI なし)。
  • graphical.target — GUI 付きマルチユーザーシステム。
  • rescue.target — シングルユーザーレスキューモード。

重要ポイント

  • systemd は最新の Ubuntu の init システム。ユニットファイルでサービス、ソケット、タイマーなどを管理。
  • systemctl start|stop|restart|status|enable|disable でサービスを管理。
  • ユニットファイルには3つのセクション:[Unit] は依存関係、[Service] は実行、[Install] はブート統合。
  • journalctl は強力なログクエリを提供。
  • ターゲットはユニットをシステム状態にグループ化。multi-user.target がサーバーのデフォルト。

次のステップ

レッスン6では、APT によるパッケージ管理について学びます。Ubuntu でソフトウェアパッケージをインストール、更新、管理する方法を学びます。

You Missed