Skip to content

Service Management

Overview

Services (also called daemons) are programs running in the background that provide various system functions. Modern Linux systems use systemd as init system and service manager.

systemd Introduction

systemd is the init system for most modern Linux distributions, responsible for:

  • Booting the system
  • Managing services
  • Managing mount points
  • Managing devices
  • Managing logs

Core Concepts

ConceptDescription
UnitBasic unit managed by systemd
ServiceService unit, runs daemons
TargetTarget unit, combines multiple units
SocketSocket unit, manages sockets
TimerTimer unit, scheduled tasks

Unit File Locations

PathDescription
/lib/systemd/system/System unit files
/etc/systemd/system/Administrator custom units
/run/systemd/system/Runtime units
~/.config/systemd/user/User units

systemctl Commands

Managing Services

bash
# Start service
$ sudo systemctl start nginx

# Stop service
$ sudo systemctl stop nginx

# Restart service
$ sudo systemctl restart nginx

# Reload configuration (don't interrupt service)
$ sudo systemctl reload nginx

# Reload or restart
$ sudo systemctl reload-or-restart nginx

# View service status
$ systemctl status nginx
 nginx.service - A high performance web server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2025-01-09 10:00:00 CST; 2h ago
  Process: 1234 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
 Main PID: 1235 (nginx)
    Tasks: 3 (limit: 4915)
   Memory: 10.0M
   CGroup: /system.slice/nginx.service
           ├─1235 nginx: master process /usr/sbin/nginx
           └─1236 nginx: worker process

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

# Check if service failed
$ systemctl is-failed nginx
active

Enable at Boot

bash
# Enable auto-start at boot
$ sudo systemctl enable nginx

# Disable auto-start at boot
$ sudo systemctl disable nginx

# Enable and start immediately
$ sudo systemctl enable --now nginx

# Disable and stop immediately
$ sudo systemctl disable --now nginx

# Check if enabled
$ systemctl is-enabled nginx
enabled

# Mask service (completely prevent from starting)
$ sudo systemctl mask nginx

# Unmask
$ sudo systemctl unmask nginx

List Services

bash
# List all services
$ systemctl list-units --type=service

# List running services
$ systemctl list-units --type=service --state=running

# List installed services
$ systemctl list-unit-files --type=service

# List failed services
$ systemctl list-units --failed

# List all units
$ systemctl list-units

# List dependencies
$ systemctl list-dependencies nginx

System Status

bash
# View system status
$ systemctl status

# Reload systemd configuration
$ sudo systemctl daemon-reload

# View default target
$ systemctl get-default
graphical.target

# Set default target
$ sudo systemctl set-default multi-user.target  # Multi-user (no graphics)
$ sudo systemctl set-default graphical.target   # Graphical interface

# Switch runlevel
$ sudo systemctl isolate multi-user.target
$ sudo systemctl isolate graphical.target

Power Management

bash
# Shutdown
$ sudo systemctl poweroff

# Restart
$ sudo systemctl reboot

# Suspend
$ sudo systemctl suspend

# Hibernate
$ sudo systemctl hibernate

# Hybrid-suspend
$ sudo systemctl hybrid-sleep

Writing Service Unit Files

Basic Structure

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

[Service]
Type=simple
ExecStart=/usr/bin/myapp
Restart=always

[Install]
WantedBy=multi-user.target

[Unit] Section

ini
[Unit]
Description=Service description
Documentation=https://example.com/docs
After=network.target mysql.service
Requires=mysql.service
Wants=redis.service
Conflicts=other.service
OptionDescription
DescriptionService description
DocumentationDocumentation links
AfterStart after specified unit
BeforeStart before specified unit
RequiresRequired units (fail if unavailable)
WantsOptional dependencies (failure doesn't affect)
ConflictsConflicting units

[Service] Section

ini
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www
ExecStart=/usr/bin/myapp --config /etc/myapp.conf
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
EnvironmentFile=/etc/myapp/env
OptionDescription
TypeService type
User/GroupRun user/group
WorkingDirectoryWorking directory
ExecStartStart command
ExecStopStop command
ExecReloadReload command
RestartRestart policy
RestartSecRestart interval
EnvironmentEnvironment variables
EnvironmentFileEnvironment variable file

Type Types

TypeDescription
simpleDefault, main process is service process
forkingService forks then parent exits
oneshotOne-time task
notifyService sends notification when ready
idleWait for other tasks to complete

Restart Policies

PolicyDescription
noDon't restart
alwaysAlways restart
on-successRestart on successful exit
on-failureRestart on failure
on-abnormalRestart on abnormal exit
on-abortRestart on abort signal

[Install] Section

ini
[Install]
WantedBy=multi-user.target
Alias=myservice.service
OptionDescription
WantedByTarget that depends on this unit
RequiredByTarget that requires this unit
AliasAlternative names

Example: Node.js Application

ini
# /etc/systemd/system/myapp.service
[Unit]
Description=My Node.js Application
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=myapp
Environment=NODE_ENV=production
Environment=PORT=3000

[Install]
WantedBy=multi-user.target

Example: Python Application

ini
# /etc/systemd/system/flask-app.service
[Unit]
Description=Flask Application
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/flask-app
Environment="PATH=/var/www/flask-app/venv/bin"
ExecStart=/var/www/flask-app/venv/bin/gunicorn --workers 3 --bind unix:flask-app.sock -m 007 app:app
Restart=always

[Install]
WantedBy=multi-user.target

Creating and Enabling Service

bash
# 1. Create service file
$ sudo vim /etc/systemd/system/myapp.service

# 2. Reload systemd
$ sudo systemctl daemon-reload

# 3. Start service
$ sudo systemctl start myapp

# 4. Check status
$ systemctl status myapp

# 5. Enable auto-start
$ sudo systemctl enable myapp

Viewing Logs

journalctl

bash
# View all logs
$ journalctl

# View specific service logs
$ journalctl -u nginx

# Follow logs in real-time
$ journalctl -u nginx -f

# View today's logs
$ journalctl --since today

# View last 1 hour
$ journalctl --since "1 hour ago"

# View specific time range
$ journalctl --since "2025-01-09 10:00:00" --until "2025-01-09 12:00:00"

# View last 100 lines
$ journalctl -n 100

# View kernel logs
$ journalctl -k

# View boot logs
$ journalctl -b
$ journalctl -b -1  # Last boot

# Filter by priority
$ journalctl -p err  # Errors and above

# Output as JSON
$ journalctl -u nginx -o json-pretty

# View disk usage
$ journalctl --disk-usage

# Clean old logs
$ sudo journalctl --vacuum-time=7d  # Keep 7 days
$ sudo journalctl --vacuum-size=500M  # Keep 500MB

Scheduled Tasks: Timer

Timer Unit File

ini
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=daily
OnCalendar=*-*-* 03:00:00
Persistent=true
Unit=backup.service

[Install]
WantedBy=timers.target

Timer Time Format

bash
# Fixed interval
OnBootSec=5min           # Start 5 minutes after boot
OnUnitActiveSec=1h       # 1 hour after last run

# Calendar time
OnCalendar=hourly        # Every hour
OnCalendar=daily         # Every day
OnCalendar=weekly        # Every week
OnCalendar=monthly        # Every month
OnCalendar=*-*-* 03:00:00    # Every day at 3 AM
OnCalendar=Mon *-*-* 09:00:00  # Every Monday at 9 AM

Managing Timer

bash
# List all timers
$ systemctl list-timers

# Start timer
$ sudo systemctl start backup.timer

# Enable auto-start
$ sudo systemctl enable backup.timer

# View timer status
$ systemctl status backup.timer

Traditional init Systems

service Command

bash
# Start service
$ sudo service nginx start

# Stop service
$ sudo service nginx stop

# Restart service
$ sudo service nginx restart

# View status
$ sudo service nginx status

# List all services
$ service --status-all

update-rc.d (Debian Family)

bash
# Enable auto-start
$ sudo update-rc.d nginx defaults

# Disable auto-start
$ sudo update-rc.d nginx disable

Summary

This chapter introduced Linux service management:

  • systemctl commands: Start, stop, restart, enable services
  • Writing service files: Unit, Service, Install sections
  • Log management: journalctl
  • Scheduled tasks: Timer units

systemd is the core of modern Linux systems; mastering it is an essential skill for system administration.


Previous chapter: Package Management

Next chapter: Network Basics

Content is for learning and research only.