Ubuntu Service Management
Introduction
Service management is a fundamental aspect of Ubuntu system administration. In a Linux environment like Ubuntu, many processes run in the background to handle various system functions - from network connectivity and printing services to web servers and databases. These background processes are called services or daemons.
Effectively managing these services is crucial for:
- Ensuring system stability and reliability
- Optimizing system performance
- Controlling resource usage
- Maintaining system security
- Enabling required functionality
This guide explores Ubuntu service management, focusing primarily on systemd - the modern service and system manager used in Ubuntu since version 15.04. We'll cover how to start, stop, and monitor services, understand service configurations, and implement best practices for effective service management.
Understanding Services in Ubuntu
What Are Services?
Services (also called daemons) are programs that run in the background without direct user interaction. They typically:
- Start automatically when the system boots
- Perform specific system functions
- Continue running indefinitely until stopped
Examples of common services include:
ssh
- Secure Shell server for remote accessapache2
- Web servermysql
- Database servercron
- Task schedulerufw
- Uncomplicated Firewall
Service Management Evolution
Ubuntu's service management has evolved over time:
- SysVinit: The traditional Unix initialization system
- Upstart: Used in Ubuntu 9.10 to 15.04
- systemd: The current service manager (since Ubuntu 15.04)
This guide focuses on systemd, as it's used in all current Ubuntu versions.
Systemd Fundamentals
Systemd Units
Systemd manages various system resources as "units." The most common unit types include:
- Service units (.service): System services
- Socket units (.socket): Inter-process communication sockets
- Target units (.target): Group of units (similar to runlevels)
- Timer units (.timer): Scheduled tasks (alternative to cron)
- Mount units (.mount): Filesystem mount points
Unit Files Location
Systemd unit files are stored in several locations:
/lib/systemd/system/
: System default unit files/etc/systemd/system/
: System-specific unit files (overrides defaults)/usr/lib/systemd/user/
: User default unit files~/.config/systemd/user/
: User-specific unit files
Basic Service Management Commands
Viewing Services
To list all active services:
systemctl list-units --type=service
Sample output:
UNIT LOAD ACTIVE SUB DESCRIPTION
apache2.service loaded active running Apache2 HTTP Server
avahi-daemon.service loaded active running Avahi mDNS/DNS-SD Stack
cron.service loaded active running Regular background program processing daemon
dbus.service loaded active running D-Bus System Message Bus
networkd-dispatcher.service loaded active running Dispatcher daemon for systemd-networkd
nginx.service loaded active running A high performance web server and a reverse proxy server
ssh.service loaded active running OpenBSD Secure Shell server
systemd-logind.service loaded active running Login Service
ufw.service loaded active exited Uncomplicated firewall
To see all services (including inactive):
systemctl list-units --type=service --all
To check a specific service status:
systemctl status apache2
Sample output:
● apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2023-05-09 14:32:45 UTC; 2min 33s ago
Docs: https://httpd.apache.org/docs/2.4/
Main PID: 12345 (apache2)
Tasks: 6 (limit: 4620)
Memory: 10.2M
CPU: 136ms
CGroup: /system.slice/apache2.service
├─12345 /usr/sbin/apache2 -k start
├─12346 /usr/sbin/apache2 -k start
└─12347 /usr/sbin/apache2 -k start
Starting and Stopping Services
To start a service:
sudo systemctl start apache2
To stop a service:
sudo systemctl stop apache2
To restart a service:
sudo systemctl restart apache2
To reload a service's configuration without restarting:
sudo systemctl reload apache2
To restart a service only if it's running:
sudo systemctl try-restart apache2
Enabling and Disabling Services
To configure a service to start at boot:
sudo systemctl enable apache2
To prevent a service from starting at boot:
sudo systemctl disable apache2
To enable and immediately start a service:
sudo systemctl enable --now apache2
To disable and immediately stop a service:
sudo systemctl disable --now apache2
Managing Service Dependencies
Services often depend on other services or system resources. Systemd handles these dependencies automatically.
To view a service's dependencies:
systemctl list-dependencies apache2
Sample output:
apache2.service
● ├─system.slice
● ├─apache2.socket
● ├─sysinit.target
● │ ├─apparmor.service
● │ ├─dev-hugepages.mount
● │ ├─dev-mqueue.mount
● │ ├─sys-fs-fuse-connections.mount
● │ ├─sys-kernel-config.mount
● │ └─sys-kernel-debug.mount
● ├─network-online.target
● │ └─NetworkManager-wait-online.service
● └─basic.target
● ├─paths.target
● ├─sockets.target
● │ ├─dbus.socket
Creating Custom Services
You can create your own systemd service for any application or script you want to run as a daemon.
Example: Creating a Custom Python Web Server Service
- Create a simple Python script:
sudo nano /usr/local/bin/simple_web_server.py
Add the following content:
#!/usr/bin/env python3
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f"Serving at port {PORT}")
httpd.serve_forever()
- Make the script executable:
sudo chmod +x /usr/local/bin/simple_web_server.py
- Create a systemd service file:
sudo nano /etc/systemd/system/simple-web.service
Add the following content:
[Unit]
Description=Simple Python HTTP Server
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/html
ExecStart=/usr/local/bin/simple_web_server.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
- Reload systemd to recognize the new service:
sudo systemctl daemon-reload
- Start and enable the service:
sudo systemctl enable --now simple-web
- Check the service status:
sudo systemctl status simple-web
Understanding Service Configuration
Anatomy of a Systemd Unit File
Systemd service units consist of three main sections:
- [Unit]: Basic information and dependencies
- [Service]: Service-specific configuration
- [Install]: Installation information
Let's examine a typical service file:
cat /lib/systemd/system/ssh.service
[Unit]
Description=OpenBSD Secure Shell server
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run
[Service]
EnvironmentFile=-/etc/default/ssh
ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/usr/sbin/sshd -t
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify
RuntimeDirectory=sshd
RuntimeDirectoryMode=0755
[Install]
WantedBy=multi-user.target
Alias=sshd.service
Important Unit File Options
[Unit] Section Options
- Description: Human-readable description
- Documentation: Where to find documentation
- After/Before: Order of starting services (not dependencies)
- Requires: Hard dependencies
- Wants: Soft dependencies
- Conflicts: Services that cannot run simultaneously
[Service] Section Options
- Type: Service startup type (simple, forking, oneshot, etc.)
- ExecStart: Command to start the service
- ExecStop: Command to stop the service
- ExecReload: Command to reload the service
- Restart: When to restart the service (always, on-failure, etc.)
- User/Group: Which user/group to run as
- WorkingDirectory: Working directory for the service
- Environment/EnvironmentFile: Environment variables
[Install] Section Options
- WantedBy: Which target should include this service
- Alias: Alternative names for the service
Modifying Existing Services
You should never directly edit files in /lib/systemd/system/
. Instead, create override files:
- Create an override directory:
sudo systemctl edit apache2
This opens an editor where you can add override settings:
[Service]
# Add additional environment variables
Environment="APACHE_LOG_DIR=/var/log/custom"
# Change the restart behavior
Restart=always
RestartSec=5
The changes will be saved to /etc/systemd/system/apache2.service.d/override.conf
.
- Reload systemd configuration:
sudo systemctl daemon-reload
- Restart the service for changes to take effect:
sudo systemctl restart apache2
Advanced Service Management
Managing Service Logs
Systemd includes a powerful logging system called journald that collects and manages service logs.
To view logs for a specific service:
journalctl -u apache2
To follow logs in real-time:
journalctl -u apache2 -f
To view logs since a specific time:
journalctl -u apache2 --since "2023-05-09 14:30:00"
To view logs for the current boot:
journalctl -u apache2 -b
Service Resource Management
Systemd allows you to set resource limits for services using "cgroups" (control groups).
To create resource limitations, edit the service or create an override:
sudo systemctl edit apache2
Add resource constraints:
[Service]
# Limit CPU usage
CPUQuota=50%
# Limit memory usage
MemoryLimit=512M
# Limit I/O
IOWeight=500
Socket Activation
Socket activation allows services to start on-demand when a connection is made, saving resources.
A simple socket unit example:
[Unit]
Description=My Service Socket
[Socket]
ListenStream=12345
Accept=yes
[Install]
WantedBy=sockets.target
Service Timers
Systemd timers can replace traditional cron jobs for scheduled tasks:
- Create a service file:
sudo nano /etc/systemd/system/backup.service
[Unit]
Description=Daily Backup Service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup-script.sh
User=backup
- Create a timer file:
sudo nano /etc/systemd/system/backup.timer
[Unit]
Description=Run backup daily at 2am
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
- Enable the timer:
sudo systemctl enable --now backup.timer
- List active timers:
systemctl list-timers
Troubleshooting Service Issues
Common Service Problems and Solutions
- Service fails to start
Check logs for error messages:
journalctl -u my-service -n 50
Check for configuration errors:
sudo my-service-binary --check-config
- Service starts but crashes immediately
Look for resource issues:
journalctl -u my-service | grep -i "out of memory"
Check permissions:
ls -la /path/to/service/files
- Service won't enable at boot
Check for dependency issues:
systemctl list-dependencies --reverse my-service
Verify installation target:
grep "WantedBy" /etc/systemd/system/my-service.service
Service Recovery Techniques
- Reset failed service status:
sudo systemctl reset-failed my-service
- Force stop a service:
sudo systemctl kill -s SIGKILL my-service
- Reload all unit files:
sudo systemctl daemon-reload
Best Practices for Service Management
- Always use systemctl commands rather than directly manipulating service files or processes
- Create override files instead of editing default unit files
- Set appropriate resource limits to prevent service issues
- Implement proper logging for troubleshooting
- Use socket activation for infrequently used services
- Implement service monitoring for critical services
- Document custom services for future reference
- Regularly check service status as part of system maintenance
- Keep services updated to patch security vulnerabilities
- Disable unnecessary services to reduce attack surface
Practical Examples
Example 1: Securing an SSH Service
To enhance SSH security by changing the port and limiting login attempts:
- Create an override file:
sudo systemctl edit ssh
- Add custom options:
[Service]
# Add environment variable for SSH port
Environment="SSH_PORT=2222"
# Pass it to the command
ExecStart=
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS -p ${SSH_PORT}
- Edit SSH configuration:
sudo nano /etc/ssh/sshd_config
- Add fail2ban protection:
sudo apt install fail2ban
sudo nano /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
- Restart services:
sudo systemctl restart ssh
sudo systemctl restart fail2ban
Example 2: Setting Up a Web Server with Custom Directories
- Install Apache:
sudo apt install apache2
- Create an override file:
sudo systemctl edit apache2
- Configure custom directories:
[Service]
Environment=APACHE_LOG_DIR=/var/log/custom-apache
Environment=APACHE_RUN_DIR=/var/run/custom-apache
Environment=APACHE_LOCK_DIR=/var/lock/custom-apache
# Create required directories on startup
ExecStartPre=/bin/mkdir -p ${APACHE_LOG_DIR} ${APACHE_RUN_DIR} ${APACHE_LOCK_DIR}
ExecStartPre=/bin/chown www-data:www-data ${APACHE_LOG_DIR} ${APACHE_RUN_DIR} ${APACHE_LOCK_DIR}
- Restart Apache:
sudo systemctl restart apache2
Summary
Ubuntu service management through systemd provides a powerful, flexible way to control background processes on your system. By understanding how to start, stop, enable, and configure services, you can maintain a stable and secure Ubuntu system.
Key takeaways:
- Services are background processes that perform specific system functions
- Systemd is the current service manager in Ubuntu
- Basic commands include
systemctl start
,stop
,enable
, andstatus
- Service configuration is done through unit files
- Custom services can be created for your own applications
- Systemd provides powerful logging, resource management, and scheduling capabilities
Further Resources
Documentation
Practice Exercises
- Create a custom service for a simple application
- Modify an existing service to use different resource limits
- Set up a systemd timer to run a daily backup script
- Configure a socket-activated service
- Troubleshoot and fix a failing service
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)