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
| Concept | Description |
|---|---|
| Unit | Basic unit managed by systemd |
| Service | Service unit, runs daemons |
| Target | Target unit, combines multiple units |
| Socket | Socket unit, manages sockets |
| Timer | Timer unit, scheduled tasks |
Unit File Locations
| Path | Description |
|---|---|
/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
activeEnable 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 nginxList 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 nginxSystem 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.targetPower Management
bash
# Shutdown
$ sudo systemctl poweroff
# Restart
$ sudo systemctl reboot
# Suspend
$ sudo systemctl suspend
# Hibernate
$ sudo systemctl hibernate
# Hybrid-suspend
$ sudo systemctl hybrid-sleepWriting 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| Option | Description |
|---|---|
| Description | Service description |
| Documentation | Documentation links |
| After | Start after specified unit |
| Before | Start before specified unit |
| Requires | Required units (fail if unavailable) |
| Wants | Optional dependencies (failure doesn't affect) |
| Conflicts | Conflicting 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| Option | Description |
|---|---|
| Type | Service type |
| User/Group | Run user/group |
| WorkingDirectory | Working directory |
| ExecStart | Start command |
| ExecStop | Stop command |
| ExecReload | Reload command |
| Restart | Restart policy |
| RestartSec | Restart interval |
| Environment | Environment variables |
| EnvironmentFile | Environment variable file |
Type Types
| Type | Description |
|---|---|
| simple | Default, main process is service process |
| forking | Service forks then parent exits |
| oneshot | One-time task |
| notify | Service sends notification when ready |
| idle | Wait for other tasks to complete |
Restart Policies
| Policy | Description |
|---|---|
| no | Don't restart |
| always | Always restart |
| on-success | Restart on successful exit |
| on-failure | Restart on failure |
| on-abnormal | Restart on abnormal exit |
| on-abort | Restart on abort signal |
[Install] Section
ini
[Install]
WantedBy=multi-user.target
Alias=myservice.service| Option | Description |
|---|---|
| WantedBy | Target that depends on this unit |
| RequiredBy | Target that requires this unit |
| Alias | Alternative 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.targetExample: 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.targetCreating 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 myappViewing 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 500MBScheduled 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.targetTimer 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 AMManaging 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.timerTraditional 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-allupdate-rc.d (Debian Family)
bash
# Enable auto-start
$ sudo update-rc.d nginx defaults
# Disable auto-start
$ sudo update-rc.d nginx disableSummary
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