Published on

Linux Services

Authors

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:

CategoryDescriptionExamples
System ServicesCore services essential for the Linux operating system’s functionality.systemd, sshd, dbus, udevd
Network ServicesServices that manage networking and communication between systems or devices.sshd, httpd (Apache), nginx, dnsmasq
Database ServicesServices that provide and manage database systems.postgresql, mysqld, mariadb
Container ServicesServices related to containerization and virtualization.docker, containerd, libvirtd
Security ServicesServices that manage system security, access control, and monitoring.firewalld, fail2ban, AppArmor
Storage ServicesServices that manage file systems, block storage, or network-attached storage.nfs, glusterfs, ceph, minio
Monitoring ServicesServices that monitor system health, performance, and availability.prometheus, grafana, nagios, zabbix
Scheduling ServicesServices that schedule and manage automated tasks.cron, atd, anacron
Desktop ServicesServices 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: systemd manages the entire lifecycle of services in modern Linux, while dbus allows 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: sshd enables remote login via SSH, while nginx and apache2 serve 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: docker and containerd manage containerized applications, while libvirtd manages 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: firewalld configures firewall rules dynamically, and fail2ban helps 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:

CommandDescription
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=serviceLists all active services on the system.
systemctl daemon-reloadReloads 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.

CommandDescription
journalctl -u <service_name>View logs for a specific service.
journalctl -u <service_name> -n 10View 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 -xeView 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
  1. 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
    
  2. 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.target
    
  3. Reload systemd to apply changes:

    sudo systemctl daemon-reload
    
  4. Enable and start the service:

    sudo systemctl enable myapp
    sudo systemctl start myapp
    
  5. Check 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
DirectiveDescription
PrivateTmp=trueGives the service its own private /tmp and /var/tmp directories.
ProtectSystem=fullMakes the entire filesystem read-only except for /etc, /var, and /home.
NoNewPrivileges=truePrevents the service from gaining additional privileges during execution.
RestrictAddressFamilies=AF_INETLimits 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:

  1. What is a Service?: A Linux service is a background process, often a daemon, that performs essential system tasks.
  2. Service Categories: Services can be categorized by their function, such as system services, network services, and security services.
  3. Systemd as Service Manager: The systemctl command is used to manage services under systemd, the most common service manager in modern Linux.
  4. Creating and Managing Services: You can create your own custom services by defining unit files in systemd.
  5. Logging and Monitoring: Use journalctl to view logs for services and troubleshoot issues.
  6. 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.