- Published on
Linux Services
- Authors

- Name
- Antoine Fusilier
- @antoinefusilier
1. What is a Linux Service?
A Linux service is a program that runs in the background and provides essential functionality to the system or other applications. These services typically do not have direct user interaction (unlike, for example, desktop applications). Instead, they manage core system operations such as networking, logging, resource management, scheduling tasks, and even running application servers.
Technically, services in Linux are referred to as daemons. These are processes that continue running after being launched, and they usually have names that end in the letter d (e.g., sshd, cron, systemd).
Key Characteristics of Linux Services:
- Background Execution: Services run in the background, independent of user login.
- Autostart: Services typically start automatically during system boot.
- Managed via Init Systems: Services are controlled, started, stopped, and managed using initialization (init) systems, such as systemd.
- Essential for System Operation: Critical services handle networking, security, file system access, logging, etc.
Service vs Process:
A process is any running instance of a program. While all services are processes, not all processes are services. Services are designed to run in the background and perform system-level tasks.
2. Types of Services
Services in Linux can be broadly classified into categories based on their purpose and function:
| Category | Description | Examples |
|---|---|---|
| System Services | Core services essential for the Linux operating system’s functionality. | systemd, sshd, dbus, udevd |
| Network Services | Services that manage networking and communication between systems or devices. | sshd, httpd (Apache), nginx, dnsmasq |
| Database Services | Services that provide and manage database systems. | postgresql, mysqld, mariadb |
| Container Services | Services related to containerization and virtualization. | docker, containerd, libvirtd |
| Security Services | Services that manage system security, access control, and monitoring. | firewalld, fail2ban, AppArmor |
| Storage Services | Services that manage file systems, block storage, or network-attached storage. | nfs, glusterfs, ceph, minio |
| Monitoring Services | Services that monitor system health, performance, and availability. | prometheus, grafana, nagios, zabbix |
| Scheduling Services | Services that schedule and manage automated tasks. | cron, atd, anacron |
| Desktop Services | Services for managing graphical user interfaces and desktop environments. | gdm, lightdm, pulseaudio |
2.1 System Services
System services are critical for the OS's core functionality. These include the service manager itself (such as systemd) and essential services like networking and device management.
- Example:
systemdmanages the entire lifecycle of services in modern Linux, whiledbusallows inter-process communication between system components.
2.2 Network Services
Network services enable communication between different systems. These include web servers, DNS services, and remote login services.
- Example:
sshdenables remote login via SSH, whilenginxandapache2serve web content over HTTP/HTTPS.
2.3 Container and Virtualization Services
Container services manage container runtimes and virtual machines. Containers are lightweight, portable environments that run isolated applications.
- Example:
dockerandcontainerdmanage containerized applications, whilelibvirtdmanages virtual machines.
2.4 Security Services
Security services control access to the system, monitor for intrusions, and protect against attacks. They can also manage firewalls and user permissions.
- Example:
firewalldconfigures firewall rules dynamically, andfail2banhelps prevent brute force attacks by banning malicious IP addresses.
3. The Service Lifecycle: Management with systemd
Modern Linux distributions primarily use systemd to manage services. Systemd controls the service lifecycle: starting, stopping, and monitoring services. It also handles service dependencies and ensures services start in the correct order.
3.1 Systemd Units
A unit in systemd is a representation of a service or system resource. There are different types of units, but the most common are service units (.service). Unit files are stored in directories like:
/etc/systemd/system/(for user-installed services)/lib/systemd/system/(for system-installed services)
3.2 Unit File Structure
Here’s an example of a systemd service unit file:
[Unit]
Description=My Custom Service
After=network.target
[Service]
ExecStart=/usr/bin/my-service-start
ExecStop=/usr/bin/my-service-stop
Restart=on-failure
[Install]
WantedBy=multi-user.target
- [Unit]: Defines the service description and dependencies.
- [Service]: Specifies how to start and stop the service, and what to do if the service fails.
- [Install]: Defines how and when the service should be installed or enabled.
3.3 Managing Services with systemd
Systemd provides the systemctl command for managing services:
| Command | Description |
|---|---|
systemctl start <service_name> | Starts the service immediately. |
systemctl stop <service_name> | Stops the service. |
systemctl restart <service_name> | Restarts the service. |
systemctl reload <service_name> | Reloads the service without stopping it. |
systemctl enable <service_name> | Enables the service to start at boot. |
systemctl disable <service_name> | Disables the service from starting at boot. |
systemctl status <service_name> | Shows the current status of the service. |
systemctl list-units --type=service | Lists all active services on the system. |
systemctl daemon-reload | Reloads systemd when unit files are modified. |
3.4 Service States
A service can be in one of the following states:
- Active: The service is running.
- Inactive: The service is not running.
- Failed: The service has encountered an error.
- Reloading: The service configuration is being reloaded without restarting the process.
4. Logs and Monitoring
Linux services generate logs that can be essential for diagnosing issues. These logs are managed by systemd’s journal using journalctl.
4.1 Viewing Logs with journalctl
journalctl is a powerful tool to view logs from systemd-managed services.
| Command | Description |
|---|---|
journalctl -u <service_name> | View logs for a specific service. |
journalctl -u <service_name> -n 10 | View the last 10 log entries for a service. |
journalctl -u <service_name> --since "1 hour ago" | View logs for a service within the last hour. |
journalctl -xe | View logs for the entire system, starting with the most recent entries. |
4.2 Log Rotation with logrotate
Services that produce a large number of logs can be configured to use logrotate, a utility that rotates, compresses, and deletes old logs to save disk space. Logrotate configuration files are typically found in /etc/logrotate.d/.
Example of a logrotate configuration:
/var/log/myapp.log {
weekly
rotate 4
compress
missingok
notifempty
create 0640 root adm
}
- weekly: Rotate the logs every week.
- rotate 4: Keep 4 weeks of logs.
- compress: Compress old logs.
- create: Create new log files with specified permissions.
5. Creating Custom Services
Linux allows users to create their own services using systemd unit files. Here’s a detailed guide on creating a custom service.
5.1 Steps to Create a Custom Service
Create a service file:
- Place the service file in
/etc/systemd/system/. For example,/etc/systemd/system/myapp.service.
sudo nano /etc/systemd/system/myapp.service- Place the service file in
Define the service:
- Use a basic systemd service unit structure:
[Unit] Description=My Custom Application After=network.target [Service] ExecStart=/usr/local/bin/myapp Restart=on-failure User=nobody Group=nogroup [Install] WantedBy=multi-user.targetReload systemd to apply changes:
sudo systemctl daemon-reloadEnable and start the service:
sudo systemctl enable myapp sudo systemctl start myappCheck the service status:
sudo systemctl status myapp
6. Dependency Management and Targets
Systemd allows defining dependencies between services, ensuring that services start in the correct order.
6.1 What is a Target?
A target is a special type of systemd unit that groups together multiple services. For example, the multi-user.target target represents a non-graphical multi-user environment, while the graphical.target target starts the graphical user interface.
6.2 Defining Service Dependencies
Services can depend on other services or targets using the After=, Before=, Requires=, or Wants= directives.
- After=: Specifies that the service should start after another service or target.
- Requires=: The service will fail if the required service is not running.
- Wants=: A soft dependency. If the dependent service is not running, the main service will still start.
Example:
[Unit]
Description=My Application
After=network.target
Wants=docker.service
In this example, the service will start after the network is available and attempts to start Docker.
7. Service Security with systemd
systemd provides built-in security features to sandbox and restrict services, enhancing system security. You can restrict what resources a service can access, including filesystem access, network access, and user permissions.
7.1 Security Options for Services
| Directive | Description |
|---|---|
PrivateTmp=true | Gives the service its own private /tmp and /var/tmp directories. |
ProtectSystem=full | Makes the entire filesystem read-only except for /etc, /var, and /home. |
NoNewPrivileges=true | Prevents the service from gaining additional privileges during execution. |
RestrictAddressFamilies=AF_INET | Limits the service to only communicate over the specified address family (e.g., AF_INET for IPv4). |
Example:
[Service]
ExecStart=/usr/bin/myapp
PrivateTmp=true
ProtectSystem=full
NoNewPrivileges=true
This configuration restricts the service’s access to the file system and prevents privilege escalation.
8. Performance Monitoring and Resource Control
Systemd provides resource control using cgroups (control groups), which can limit a service's use of CPU, memory, and I/O.
8.1 Resource Limiting with systemd
You can configure limits for CPU and memory usage in the [Service] section of a unit file.
- MemoryLimit=: Sets a memory usage limit for the service.
- CPUQuota=: Restricts CPU usage as a percentage.
Example:
[Service]
ExecStart=/usr/bin/myapp
MemoryLimit=500M
CPUQuota=50%
This restricts the service to 500 MB of memory and 50% of the CPU.
9. Summary and Conclusion
Linux services, also known as daemons, are the backbone of the operating system, running in the background to handle everything from networking to security to resource management. With the evolution of systemd, managing these services has become more powerful, flexible, and easier to control, providing a range of tools to automate, secure, and monitor service operations.
Key Takeaways:
- What is a Service?: A Linux service is a background process, often a daemon, that performs essential system tasks.
- Service Categories: Services can be categorized by their function, such as system services, network services, and security services.
- Systemd as Service Manager: The
systemctlcommand is used to manage services under systemd, the most common service manager in modern Linux. - Creating and Managing Services: You can create your own custom services by defining unit files in systemd.
- Logging and Monitoring: Use
journalctlto view logs for services and troubleshoot issues. - Security and Resource Management: systemd provides built-in mechanisms for sandboxing and limiting service resources.
By mastering Linux services, you unlock the full potential of managing a modern Linux system, ensuring performance, security, and scalability in a range of environments, from local development to large-scale cloud deployments.