Chapter 2.7 - Services and Daemons
Learning Objectives
By the end of this chapter, you will be able to:
- Understand Linux services and daemons
- Manage services with systemd
- Create custom services
- Understand systemd unit files
What is a Service/Daemon?
A service (or daemon) is a program that runs in the background, usually without a user interface, to provide system or network functionalities.
Types of Services
System Services
Essential services for system operation:
- sshd: SSH Server
- systemd-logind: Session management
- NetworkManager: Network management
Network Services
Services that listen on the network:
- apache2/nginx: Web servers
- mysql/postgresql: Databases
- bind9: DNS server
User Services
Services launched by the user:
- pulseaudio: Audio
- dbus: Inter-process communication
Management with systemd
systemctl Commands
# View the status of a service
systemctl status apache2
# Start a service
systemctl start apache2
# Stop a service
systemctl stop apache2
# Restart a service
systemctl restart apache2
# Reload the configuration
systemctl reload apache2
# Enable at startup
systemctl enable apache2
# Disable at startup
systemctl disable apache2
# View all services
systemctl list-units --type=service
# View active services
systemctl list-units --type=service --state=running
Unit Files
Services are defined by unit files in /etc/systemd/system/ or /lib/systemd/system/:
Example of a simple service:
[Unit]
Description=My Custom Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/my-service
Restart=always
User=myuser
[Install]
WantedBy=multi-user.target
Sections:
- [Unit]: Metadata and dependencies
- [Service]: Service configuration
- [Install]: Installation and activation
Types of Services
Simple Type
Service that starts and remains active:
Type=simple
ExecStart=/usr/bin/my-service
Forking Type
Service that forks and the parent terminates:
Type=forking
ExecStart=/usr/bin/my-service
PIDFile=/var/run/my-service.pid
Oneshot Type
Service that runs once and terminates:
Type=oneshot
ExecStart=/usr/bin/script-init
RemainAfterExit=yes
Dependencies
Services can have dependencies:
[Unit]
Description=Web Service
After=network.target mysql.service
Requires=mysql.service
Wants=redis.service
Directives:
- After: Starts after these services
- Before: Starts before these services
- Requires: Mandatory dependency
- Wants: Optional dependency
Summary
In this chapter, you learned:
Services/Daemons: Background programs
systemd: Modern service manager
systemctl: Management commands
Unit files: Service configuration
Dependencies: After, Before, Requires, Wants
Types: simple, forking, oneshot
Next Steps
Chapter 2.8: Runlevels
Chapter 2.9: Boot Process
Chapter created on: December 2024