Intro
Systemd has become the default init system and service manager on most modern Linux distributions, including Ubuntu, Debian, Fedora, CentOS/RHEL, and Arch. It manages services, sockets, devices, mounts, and more. As a developer, DevOps engineer, or system administrator, you need visibility into what systemd is doing: which services are running, which have failed, and why. This guide provides practical monitoring and alerting techniques for systemd. We will cover how to inventory your systemd environment, collect key metrics, configure alerts, diagnose failures, and establish recovery procedures. Every command and configuration is ready to use, with placeholders that you can adapt to your environment.
Throughout this guide, we will use systemd version 249 (the default on Ubuntu 22.04 LTS) as a reference. Most commands work on systemd 245 and later. We will highlight version-specific differences where relevant. Before you begin, ensure you have:
- A Linux system with systemd (version 245 or later recommended).
- Sudo or root access to run systemctl and edit unit files.
- Basic familiarity with the command line and systemd unit files.
We will focus on operational safety: observe before changing, limit the blast radius, avoid exposing secrets, verify results, and document recovery paths.
Version and Environment Inventory
Before you can monitor systemd effectively, you must know what you are working with. Start by identifying the systemd version, the running services, and the overall state of the system.
Check Systemd Version and System Information
Run the following commands to gather version and environment details:
systemctl --version
Example output on Ubuntu 22.04:
systemd 249 (249.11-0ubuntu3.12)
+PAM +AUDIT +SELINUX +APPARMOR +IMA +SMACK +SECCOMP +GCRYPT +GNUTLS +OPENSSL +ACL +BLKID +CURL +ELFUTILS +FIDO2 +IDN2 -IDN +IPTC +KMOD +LIBCRYPTSETUP +LIBFDISK +PCRE2 -PWQUALITY -P11KIT -QRENCODE +BZIP2 +LZ4 +XZ +ZLIB +ZSTD -XKBCOMMON +UTMP +SYSVINIT default-hierarchy=unified
This tells you the exact version, which is critical for determining feature availability. For example, cgroup v2 features are available only with the unified hierarchy, which is the default on Ubuntu 22.04 but not on older releases.
Next, check the overall system state:
systemctl status
This shows a summary of the system state, including the number of failed units, if any. Example output:
● myhost
State: running
Jobs: 0 queued
Failed: 0 units
Since: Wed 2025-03-19 10:15:22 UTC; 1 day 4h ago
CGroup: /
├─user.slice
│ └─user-1000.slice
│ ├─session-3.scope
│ │ ├─1234 sshd: user [priv]
│ │ └─5678 sshd: user@pts/0
│ └─[email protected]
│ ├─init.scope
│ │ ├─1000 /lib/systemd/systemd --user
│ │ └─1001 (sd-pam)
│ └─...
├─init.scope
│ └─1 /sbin/init splash
└─system.slice
├─ssh.service
│ └─890 /usr/sbin/sshd -D
├─cron.service
│ └─901 /usr/sbin/cron -f
└─...
List Services and Their States
To see all active services:
systemctl list-units --type=service --state=active
Or all services regardless of state:
systemctl list-units --type=service --all
The output columns are: UNIT (service name), LOAD (loaded or not), ACTIVE (active, inactive, failed, etc.), SUB (running, exited, dead, etc.), and DESCRIPTION.
Example:
UNIT LOAD ACTIVE SUB DESCRIPTION
accounts-daemon.service loaded active running Accounts Service
apparmor.service loaded active exited Load AppArmor profiles
apport.service loaded active exited LSB: automatic crash report generation
atd.service loaded active running Deferred execution scheduler
cron.service loaded active running Regular background program processing daemon
dbus.service loaded active running D-Bus System Message Bus
To identify failed services specifically:
systemctl list-units --type=service --state=failed
Identify Deployment Topology
You also need to know how systemd is deployed. Is this a physical server, a virtual machine, or a container? Is it a single node or part of a cluster? For containers, systemd might not be PID 1, which changes monitoring approaches. Check if systemd is PID 1:
ps -p 1 -o comm=
If the output is systemd, it is PID 1. In Docker containers, unless systemd is explicitly run, it will not be PID 1, and most systemd features will not work. In that case, you might need to monitor the container orchestration layer instead.
Understand the critical services on the host. For example, if you are running a web server, the nginx.service or apache2.service is critical. Identify the units that are essential for your application and note their dependencies.
Read-Only Observation
All commands so far are read-only; they do not change system state. Always capture these outputs before making any changes. Record the timestamp, the command, and the output. This provides a baseline for later comparison.
Expected Results and Failure Signals
For each monitored service, define what "healthy" looks like. For example, a healthy nginx.service should be active (running) and its main process should be the nginx master process. A failure signal could be active (exited) with an error, or failed. Knowing these signals lets you configure alerts accordingly.
Safe Configuration Path
Monitoring systemd often requires configuring the systemd journal, adding metrics exporters, or setting up alerting rules. Follow a safe configuration path to avoid breaking services.
Configuring the Journal for Reliable Logging
The systemd journal is the central log repository. For monitoring and alerting, you want journal logs to be persistent and optionally forwarded to a central log server.
Check the current journal configuration:
journalctl --verify
This checks journal file consistency. To see if the journal is persistent:
ls -ld /var/log/journal
If the directory exists, the journal is persistent; if not, it is volatile (stored in /run/log/journal, lost on reboot). To make it persistent, create the directory and restart systemd-journald:
sudo mkdir -p /var/log/journal
sudo systemd-tmpfiles --create --prefix /var/log/journal
sudo systemctl restart systemd-journald
Blast radius: This change affects logging only. It increases disk usage, so ensure you have enough space. Verify by checking the directory and service status:
ls -ld /var/log/journal
systemctl status systemd-journald
Expected output: the directory exists and systemd-journald is active (running).
Forwarding Journal Logs to a Central Server
For centralized monitoring, forward journal entries to a syslog server or a log aggregator like Elasticsearch, Loki, or Graylog. systemd-journald can forward to syslog via the ForwardToSyslog option, and rsyslog or syslog-ng can then forward to remote servers.
Edit /etc/systemd/journald.conf (or a drop-in file) to set:
[Journal]
ForwardToSyslog=yes
Create a drop-in directory to preserve defaults:
sudo mkdir -p /etc/systemd/journald.conf.d
sudo tee /etc/systemd/journald.conf.d/forward.conf > /dev/null <<EOF
[Journal]
ForwardToSyslog=yes
EOF
sudo systemctl restart systemd-journald
Then configure rsyslog to forward logs. Add to /etc/rsyslog.d/50-forward.conf:
*.* @logs.example.com:514
Replace logs.example.com with your log server. Restart rsyslog:
sudo systemctl restart rsyslog
Blast radius: This changes logging flow. If the remote server is unreachable, rsyslog may queue logs in memory and potentially drop if queue is full. Verify by checking rsyslog status and test connection:
systemctl status rsyslog
logger -n logs.example.com -P 514 "Test message from $(hostname)"
The test should appear on the remote server.
Setting Up Metrics Collection
Systemd exposes metrics through cgroups and the D-Bus API. The most common approach is to use systemd-exporter for Prometheus. It collects metrics such as service states, restarts, and resource usage.
Install systemd-exporter on Ubuntu:
sudo apt install prometheus-systemd-exporter
Or download the binary from GitHub and run as a service. The exporter runs on port 9558 by default. Verify it is working:
curl http://localhost:9558/metrics | grep systemd_unit_state
Expected output includes lines like:
systemd_unit_state{name="nginx.service",state="active",type="service"} 1
Then configure Prometheus to scrape it. In prometheus.yml:
scrape_configs:
- job_name: 'systemd'
static_configs:
- targets: ['localhost:9558']
Blast radius: Adding an exporter is low risk. Ensure the port is not exposed publicly; restrict access via firewall. Verify by checking the endpoint and Prometheus targets page.
Configuring Alert Rules
Based on the metrics, define Prometheus alert rules. For example, alert when a service is not active for more than 5 minutes:
groups:
- name: systemd_alerts
rules:
- alert: SystemdServiceNotActive
expr: systemd_unit_state{state!="active"} == 1
for: 5m
labels:
severity: critical
annotations:
summary: "Service {{ $labels.name }} is {{ $labels.state }}"
description: "Service {{ $labels.name }} on {{ $labels.instance }} has been {{ $labels.state }} for over 5 minutes."
This rule fires if any non-active state persists. Adjust the for duration to avoid flapping. Test the rule by temporarily stopping a test service and checking the Prometheus alerts page.
Verification and Diagnostics
Once monitoring is set up, you need to verify that it works and diagnose issues promptly.
Verify Service Status and Health
Use systemctl status for a quick view of a service's health:
systemctl status nginx.service
The output includes the service state, main PID, recent log entries, and control group information. To check if a service is enabled to start at boot:
systemctl is-enabled nginx.service
Expected output: enabled or static. To check if it's active:
systemctl is-active nginx.service
Expected output: active.
Inspect Service Logs
Use journalctl to view logs for a specific service:
journalctl -u nginx.service -n 50 --no-pager
This shows the last 50 lines. Add -f to follow:
journalctl -u nginx.service -f
Filter by time:
journalctl -u nginx.service --since "2025-03-19 10:00:00" --until "2025-03-19 11:00:00"
Use -p to filter by priority:
journalctl -u nginx.service -p err
Shows only error and higher severity messages.
Diagnose Failed Services
For a failed service, get detailed information:
systemctl status nginx.service --full --no-pager
The --full option shows complete lines without truncation. Look for the Main PID and the last log lines. Also, check the exit code:
systemctl show nginx.service -p ExecMainStatus
If the service repeatedly fails and restarts, check the restart counters:
systemctl show nginx.service -p NRestarts -p StartLimitBurst
This helps identify crash loops.
Analyze Dependency Failures
A service may fail because its dependencies are not met. Use:
systemctl list-dependencies nginx.service
This shows required units. If a dependency failed, fix that first.
Debug with systemd-analyze
For boot-time issues, use systemd-analyze:
systemd-analyze blame
This lists units sorted by time taken to initialize. It helps find slow services. Also:
systemd-analyze critical-chain
Shows the critical chain of units that delayed boot.
Verify Metric Export
Check that the systemd exporter is returning metrics:
curl -s http://localhost:9558/metrics | grep -E 'systemd_unit_state|systemd_unit_start_time_seconds' | head -20
Ensure the metrics make sense. For example, systemd_unit_state should have a value of 1 for the active state and 0 for others.
Test Alerting Pipeline
Trigger a test alert by stopping a non-critical service:
sudo systemctl stop test-service.service
Wait for the alert to fire (based on your for duration). Check Prometheus alerts page or Alertmanager. Then restart:
sudo systemctl start test-service.service
This validates the entire monitoring pipeline.
Failure Modes and Recovery
Understanding common failure modes and how to recover is essential. Here we cover typical systemd-related failures and recovery steps.
Service Fails to Start
Symptoms: systemctl start myapp fails, status shows failed.
Diagnosis: Check logs:
journalctl -u myapp.service -n 50
Common causes:
- Incorrect command path or permissions.
- Missing environment variables.
- Port already in use.
- Configuration file syntax error.
Recovery: Fix the underlying issue, then reload systemd and start:
sudo systemctl daemon-reload
sudo systemctl start myapp.service
Verify with systemctl status myapp.service.
Service Crashes Intermittently
Symptoms: Service runs for a while then crashes, restarts repeatedly.
Diagnosis: Check restart count and logs around crash time:
systemctl show myapp.service -p NRestarts
journalctl -u myapp.service --since "10 minutes ago"
Look for OOM kills or unhandled exceptions. Check cgroup memory limit:
systemctl show myapp.service -p MemoryCurrent -p MemoryLimit
Recovery: If OOM, increase memory limit in unit file (if using MemoryMax=) or optimize application. If code bug, fix and deploy.
Service Hangs and Does Not Respond
Symptoms: Service is active but not functioning; health checks fail.
Diagnosis: Check if the service is in uninterruptible sleep (D state):
ps -o pid,stat,cmd -p $(systemctl show -p MainPID --value myapp.service)
If STAT is D, it's waiting for I/O. Check disk I/O:
iostat -x 1
Recovery: If stuck on I/O, check storage health. If unresponsive, restart the service:
sudo systemctl restart myapp.service
If restart does not work, use systemctl kill to send SIGKILL:
sudo systemctl kill -s SIGKILL myapp.service
Then start again.
Dependency Failure
Symptoms: Service fails because a required unit is not running.
Diagnosis: List dependencies and their states:
systemctl list-dependencies myapp.service --all
Recovery: Start the failed dependency, or modify the unit file to remove unnecessary dependencies. If the dependency is optional, add After= with Wants= instead of Requires= to avoid hard failure.
Journal Corruption
Symptoms: journalctl reports errors or cannot read logs.
Diagnosis: Run journalctl --verify. It reports corrupt files.
Recovery: You may need to delete corrupt journal files (only after backing up if possible):
sudo journalctl --rotate
sudo journalctl --vacuum-size=100M
If still corrupt, stop journald, remove the journal directory, and restart:
sudo systemctl stop systemd-journald
sudo rm -rf /var/log/journal/*
sudo systemctl start systemd-journald
Blast radius: This deletes all local logs. Only do this as last resort.
Systemd-exporter Metric Gaps
Symptoms: Prometheus shows no metrics from the exporter.
Diagnosis: Check exporter process and port:
sudo systemctl status prometheus-systemd-exporter
curl http://localhost:9558/metrics
Recovery: Restart exporter if down. Check firewall rules. Verify Prometheus scrape config.
Common Pitfalls and How to Avoid Them
Many operators fall into similar traps when monitoring systemd. Here are the most frequent ones and how to avoid or recover from them.
Pitfall 1: Ignoring the Journal Rotation and Retention
Why it happens: By default, the journal may be volatile or have small size limits. Operators only realize logs are missing when troubleshooting an incident.
How to avoid: Configure persistent journal and set appropriate retention. In /etc/systemd/journald.conf:
[Journal]
Storage=persistent
SystemMaxUse=500M
SystemKeepFree=1G
MaxRetentionSec=1month
Then restart journald. Verify with journalctl --disk-usage.
Pitfall 2: Over-alerting on Non-Critical Services
Why it happens: Alert rules often match all services, including ones that are intentionally stopped or oneshots that exit. This leads to alert fatigue.
How to avoid: Scope alerts to critical services only. In Prometheus, use a label filter, e.g., systemd_unit_state{name=~"nginx|mysql|redis"}. Also exclude oneshot services that exit cleanly. Create a list of critical services and review it quarterly.
Pitfall 3: Not Monitoring Service Restarts
Why it happens: A service that crashes and restarts may appear healthy between restarts, masking a problem.
How to avoid: Monitor systemd_unit_restarts_total or systemd_unit_start_time_seconds. Alert if restarts increase significantly over a short period. For example, in Prometheus rule:
expr: increase(systemd_unit_restarts_total{name="myapp.service"}[1h]) > 3
This catches crash loops.
Pitfall 4: Changing Unit Files Without Reloading
Why it happens: After editing a unit file, you forget to run systemctl daemon-reload, leading to confusion when changes don't take effect.
How to avoid: Always run sudo systemctl daemon-reload after editing any unit file, then restart the service. Verify with systemctl show to confirm the new settings are loaded.
Pitfall 5: Not Testing Recovery Procedures
Why it happens: Teams write runbooks but never test them until an actual incident, only to find they don't work.
How to avoid: Schedule regular fire drills. Simulate a service failure and follow the runbook. Time the recovery and update the documentation. For example, every quarter, stop a non-production critical service and ensure the team can recover it within the SLA.
Pitfall 6: Exposing Metrics Endpoint Publicly
Why it happens: The systemd exporter is often run with default settings and the port is exposed to the internet, leaking system information.
How to avoid: Bind the exporter to localhost only or use firewall rules. For systemd-exporter, set --web.listen-address=127.0.0.1:9558 in the service file. Verify with ss -tlnp | grep 9558 that it's not listening on 0.0.0.0.
Pitfall 7: Ignoring User Services
Why it happens: Monitoring focuses on system services, but user services (under systemd --user) can also fail and affect applications.
How to avoid: Monitor user services as well. The systemd-exporter can be configured to also collect user service metrics if run as user or if configured with --collector.user. Alternatively, use systemctl --user commands in per-user monitoring scripts.
Operations Checklist
Use this checklist to ensure your systemd monitoring and alerting is comprehensive and up to date. Assign an owner for each item and review the checklist on a regular schedule (weekly or monthly, depending on the environment's criticality).
| Item | Owner | Frequency | How to Verify |
|---|---|---|---|
| Verify systemd version and environment | Priya Shah, Platform Engineer | Monthly | systemctl --version, record output |
| Confirm journal persistence and retention | Priya Shah | Monthly | ls -ld /var/log/journal, journalctl --disk-usage |
| Check all critical services are active | On-call engineer | Daily (automated) | systemctl is-active <service> for each critical service |
| Review failed units | On-call engineer | Daily | systemctl list-units --state=failed |
| Test alerting pipeline | Marcus Chen, SRE Lead | Quarterly | Stop a test service and confirm alert fires in Alertmanager |
| Review and update alert rules | Marcus Chen | Monthly | Compare alert rules with service inventory, adjust thresholds |
| Verify systemd-exporter metrics | Priya Shah | Weekly | curl http://localhost:9558/metrics and check Prometheus target |
| Run a fire drill for a critical service failure | Entire team | Quarterly | Simulate failure, follow runbook, measure time to recovery |
| Review log forwarding to central server | Marcus Chen | Monthly | Send test message and verify in central log system |
| Update documentation and runbooks | Priya Shah | After any incident or change | Review docs in repository, ensure they match current setup |
Each item should have a clear owner. The owner is responsible for performing the check or ensuring it's automated and alerting on failure. The frequency column defines how often the check or review occurs. The verification step provides a concrete command or action to confirm the item is in the desired state.
For example, if you are the on-call engineer and you see a failed unit in your daily check, you must investigate immediately. Document the incident, identify the root cause, and update the runbook if necessary.
Conclusion
Monitoring systemd is a foundational practice for maintaining reliable Linux systems. By following the steps in this guide, you can:
- Inventory your systemd environment accurately.
- Configure persistent logging and metrics collection.
- Set up alerts that fire on real problems.
- Diagnose failures quickly using
systemctlandjournalctl. - Recover from common failure modes with tested procedures.
- Avoid common pitfalls that lead to alert fatigue or missed issues.
Start with one low-risk verification: for the most critical service on your system, run systemctl status and journalctl -u to confirm it is healthy. Then set up the systemd-exporter and a simple alert. Build from there, expanding your monitoring coverage and refining alerts over time. Regularly review your operations checklist and assign clear owners to each item.
A reliable monitoring workflow makes failures visible, protects sensitive data, limits changes to the intended resource, and defines recovery verification before an incident forces the decision. With these practices, you can operate systemd-based infrastructure with confidence.