Systemd

Systemd

Systemd is the init system and service manager for most modern Linux distributions. It provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, and offers on-demand starting of daemons.

systemctl

The primary command for controlling and managing systemd services and the system state.

systemctl [options] command [unit]

Common Commands:

Service Management:

System Management:

Unit Listing:

Examples:

# Start a service
sudo systemctl start nginx.service

# Stop a service
sudo systemctl stop nginx.service

# Restart a service
sudo systemctl restart nginx.service

# Reload service configuration (without restarting)
sudo systemctl reload nginx.service

# Check service status
systemctl status nginx.service

# Enable service to start at boot
sudo systemctl enable nginx.service

# Disable service from starting at boot
sudo systemctl disable nginx.service

# Mask a service (completely prevent it from starting)
sudo systemctl mask nginx.service

# Unmask a service
sudo systemctl unmask nginx.service

# Check if service is active
systemctl is-active nginx.service

# Check if service is enabled at boot
systemctl is-enabled nginx.service

# Show all running services
systemctl list-units --type=service --state=running

# Show all failed services
systemctl list-units --type=service --state=failed

# List all available service units
systemctl list-unit-files --type=service

# Reboot the system
sudo systemctl reboot

# Power off the system
sudo systemctl poweroff

journalctl

The command to query and display logs from the systemd journal.

journalctl [options]

Options:

Priority Levels:

  1. . emerg: System is unusable
  2. . alert: Action must be taken immediately
  3. . crit: Critical conditions
  4. . err: Error conditions
  5. . warning: Warning conditions
  6. . notice: Normal but significant condition
  7. . info: Informational
  8. . debug: Debug-level messages

Examples:

# View all logs
journalctl

# View logs for a specific service
journalctl -u nginx.service

# Follow log entries in real-time
journalctl -f

# Show only the last 50 entries
journalctl -n 50

# Show logs from current boot
journalctl -b

# Show logs from previous boot
journalctl -b -1

# Show logs with priority level err and above
journalctl -p err

# Show logs since yesterday
journalctl --since="yesterday"

# Show logs between two dates/times
journalctl --since="2023-01-01 00:00:00" --until="2023-01-02 00:00:00"

# Show kernel messages only
journalctl -k

# Show logs matching a pattern
journalctl -g "error"

# Combine filters
journalctl -u nginx.service -p err --since="1 hour ago"

# Show logs in JSON format
journalctl -o json

# Show logs with timestamp precision
journalctl -o short-precise

systemd-analyze

A tool to analyze system boot-up performance.

systemd-analyze [command]

Commands:

Examples:

# Show boot time information
systemd-analyze time

# Show service startup times
systemd-analyze blame

# Show critical chain of boot-up
systemd-analyze critical-chain

# Generate an SVG graph of the boot sequence
systemd-analyze plot > boot.svg

# Verify unit files
systemd-analyze verify unit.service

Creating Systemd Service Units

Systemd service units are defined in files with the .service extension, typically located in the /etc/systemd/system/ or /usr/lib/systemd/system/ directories.

Basic Service Unit Example:

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

[Service]
Type=simple
User=myuser
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/start.sh
Restart=on-failure
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myapp

[Install]
WantedBy=multi-user.target

Common [Unit] Section Options:

Common [Service] Section Options:

Common [Install] Section Options:

Creating and Enabling a Custom Service:

# Create a service file
sudo nano /etc/systemd/system/myapp.service

# Reload systemd to recognize the new service
sudo systemctl daemon-reload

# Start the service
sudo systemctl start myapp.service

# Check if it's running
systemctl status myapp.service

# Enable the service to start at boot
sudo systemctl enable myapp.service

systemd Targets

Targets are groups of units that define system states, similar to runlevels in SysV init.

Common Targets:

Target Management Commands:

# View default target
systemctl get-default

# Set default target
sudo systemctl set-default multi-user.target

# Switch to a different target
sudo systemctl isolate rescue.target

# List units in a target
systemctl list-dependencies multi-user.target

systemd Timers

Timers are systemd units with .timer extensions that can be used to trigger actions at specific times, similar to cron jobs.

Basic Timer Example:

[Unit]
Description=Run my script daily

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
AccuracySec=1s

[Install]
WantedBy=timers.target

Timer Management:

# List all timers
systemctl list-timers

# Start a timer
sudo systemctl start myscript.timer

# Enable a timer
sudo systemctl enable myscript.timer

Common [Timer] Section Options:

systemd Socket Activation

Socket activation allows systemd to create listening sockets and pass them to services when needed, enabling services to be started on-demand.

Basic Socket Example:

[Unit]
Description=My Socket

[Socket]
ListenStream=8080
Accept=yes

[Install]
WantedBy=sockets.target

Socket Management:

# List all sockets
systemctl list-sockets

# Start a socket
sudo systemctl start myapp.socket

# Enable a socket
sudo systemctl enable myapp.socket

systemd-nspawn

A tool for creating and managing lightweight containers.

systemd-nspawn [options] [command]

Examples:

# Boot a container from a directory
sudo systemd-nspawn -D /path/to/container --boot

# Run a command in a container
sudo systemd-nspawn -D /path/to/container ls -l

# Create a new container
sudo debootstrap --arch=amd64 bullseye /var/lib/container/debian
sudo systemd-nspawn -D /var/lib/container/debian --boot

systemd Resource Control

Systemd supports resource control through cgroups, allowing limiting resources for services.

Resource Control Settings in Unit Files:

[Service]
CPUShares=1024
MemoryLimit=1G
BlockIOWeight=500

Setting Resource Limits via Command Line:

# Set memory limit for a service
sudo systemctl set-property myapp.service MemoryLimit=1G

# Set CPU shares for a service
sudo systemctl set-property myapp.service CPUShares=1000

systemd Environment Variables

Setting and managing environment variables for systemd services.

Setting Environment Variables in Unit Files:

[Service]
Environment="VAR1=value1" "VAR2=value2"
EnvironmentFile=/etc/myapp/env

Setting Environment Variables via Command Line:

# Set environment variable for a service
sudo systemctl set-environment VAR=value

# Show environment variables
systemctl show-environment