Creating and Managing Daemon Services in Linux using Systemd

Shreyas Matade
8 min readJun 21, 2023

--

Introduction

In this article, we’ll dive into a critical component of Linux systems management — the creation of a Daemon Service using systemd. Whether you’re an experienced Linux user or new to the ecosystem, understanding daemons, particularly how to create and manage them, is a fundamental skill that can significantly enhance your Linux journey.

What is a Daemon Service?

In the realm of Unix and Unix-like operating systems like Linux, a daemon is a background process or program that is designed to perform tasks without any direct user intervention. In simpler terms, daemons are the silent workhorses of your Linux system, carrying out important tasks in the background while you interact with the user-friendly interface at the front.

These tasks can include anything from starting applications/scripts on system startup, running scheduled tasks, listening for incoming network connections, and more. When your system boots up, it’s the daemon services that are working tirelessly behind the scenes to ensure everything starts up and runs smoothly.

Why does one need Daemon Services?

Imagine having to manually start your web server every time your host server restarts, or having to personally initiate system backups at regular intervals. Not only would this be highly inefficient, it would also be near-impossible to handle as the number of tasks increases.

This is where daemon services shine. By automating these tasks and allowing them to run in the background, daemon services free us from the need to micromanage these processes. They enhance system efficiency, help in resource management, and let us focus on more important tasks at hand.

In the following sections, we’ll explore different initialization (init) systems in Linux, will se some basics around systemd (the most widely used init system today), and walk you through creating a sample daemon service step-by-step. This knowledge will empower you to take full control of your Linux system’s background processes, enhancing your overall mastery of Linux system administration.

I hope by the end of this guide, you’ll have a firm grasp on how to create and manage daemon services using systemd.

Understanding Different Init Systems

The Linux ecosystem is diverse, and so are the ways it handles its initialization processes — the steps it takes from when you press the power button until you see the login prompt.

History of Init Systems in Linux

In the beginning, there was the Unix System V init system (SysV), one of the oldest init systems in the Linux world. Named after the Unix version it originated from, SysV init processes tasks sequentially, waiting for each to complete before moving to the next.

Another noteworthy init system is Upstart, introduced by Ubuntu in 2006. It aimed to address some of SysV’s limitations, introducing event-driven capabilities that allowed simultaneous execution of some startup tasks.

Systemd vs. SysV vs. Upstart

Each of these init systems have their own strengths. SysV’s scripts are straightforward and written in shell script, making it relatively easy to manage and understand. However, handling dependencies can be quite a chore with SysV. Upstart improved on this with its event-driven approach, but it wasn’t without its complexities.

Then came systemd in 2010, which sought to address many of the shortcomings of its predecessors. As an init system and service manager, systemd is designed to provide a more efficient way of handling system startup and service management.

Why is systemd widely used today?

Systemd is now the default init system for many major Linux distributions, such as Ubuntu, Fedora, RHEL, Debian, and others. Its popularity is due to several reasons:

  1. Speed: By using parallelization, systemd starts services faster and more efficiently.
  2. Configuration: Systemd uses declarative configuration files that are easier to manage and understand.
  3. Dependencies: Systemd handles dependencies more efficiently, ensuring that services start in the correct order.
  4. Control: Systemd provides tools that give admins comprehensive control over system services and resources.

Concept of systemd units and available unit types

At the heart of systemd is the concept of “units”. Units encapsulate various system resources that systemd knows how to manage. Units are categorized into several types, each represented by a file type and responsible for a specific aspect of system functionality:

  • Service unit (.service): This represents a system service.
  • Target unit (.target): This is a group of systemd units.
  • Automount unit (.automount): This manages a filesystem automount point.
  • Device unit (.device): This represents a device recognized by the kernel.
  • Mount unit (.mount): This manages a filesystem mount point.
  • Path unit (.path): This unit type is used for path-based activation.
  • Socket unit (.socket): This is used for inter-process communication.

Understanding these unit types is key to managing system resources with systemd.

In the following section, We will focus on Service Unit and see a step-by-step guide to creating a daemon service using systemd, leveraging this knowledge of init systems and their evolution.

Creating a Daemon Service with systemd

Prerequisites: Before we begin, make sure you have the following:

An Ubuntu system with systemd installed (Systemd is the default init system on most Ubuntu versions).

Basic knowledge of Linux command-line interface.

Creating a daemon service with systemd involves writing a script (one can have application as well) for the daemon process and creating a service file for systemd to manage it.

What is a systemd service file?

A systemd service file is a unit configuration file that defines how systemd starts and manages a certain background service. This includes instructions on how to start, stop, or restart the service, under what conditions to do so, and what to do if the service fails.

Understanding the basic structure of a systemd service file

A systemd service file is composed of various sections, each serving a specific purpose:

  1. [Unit]: This section includes metadata like a human-readable description and dependencies.
  2. [Service]: This section specifies how the service should behave, including the command to start the service, the user to run it, and what to do if it fails.
  3. [Install]: This section defines the service's behavior regarding the systemctl enable and disable commands.

Step-by-step guide to creating a systemd service

Let’s create a daemon service. For this example, we’ll create a simple time tracker service (timetracker) that logs the current date and time to a file every minute.

Write a script (timetracker.sh as an example)

As I mentioned we can “daemonize” a script as well as an application. For simplicity we will take example of a script. Create a file called timetracker.sh and open it with a text editor:

#!/bin/bash
while true
do
date >> /var/log/timetracker.log
sleep 60
done

This script will append the current date and time to the timetracker.log file every 60 seconds.

Make the script executable and move it to the appropriate directory

To make the script executable, use the chmod command:code

chmod +x timetracker.sh

Next, move it to /usr/local/bin (or another directory in your PATH), so it's easily accessible:

mv timetracker.sh /usr/local/bin

Create the service file (.service file)

Now, we’ll create the systemd service file. This should be placed in the /etc/systemd/system directory, which is where systemd looks for service files. Let's call it timetracker.service:

[Unit]
Description=Time Tracker
[Service]
ExecStart=/usr/local/bin/timetracker.sh
[Install]
WantedBy=multi-user.target

Explanation of various sections and parameters in the service file

  1. Description: Under the [Unit] section, Description gives a human-readable description of the service.
  2. ExecStart: Under the [Service] section, ExecStart specifies the command that systemd will run to start the service.
  3. WantedBy: Under the [Install] section, WantedBy specifies that the service should start when the system reaches the multi-user target, i.e., when the system has finished booting.

While this example unit file is basic, it’s essential to understand that systemd is an incredibly powerful tool, capable of accommodating a wide variety of daemon requirements. Should you need to explore more sophisticated configurations, the systemd.service man page is your comprehensive guide. This manual, as with all man pages, provides detailed documentation about the service unit, including all the configurable options.

Accessing this wealth of information is straightforward: simply open a terminal and input the following command:

man systemd.service

Manage (start, stop, enable, disable) the service

Once your service file is created and saved, you can use systemctl to manage your service:

  • systemctl enable timetracker: This sets the time tracker service to start on boot.
  • systemctl start timetracker: This starts the time tracker service immediately.
  • systemctl stop timetracker: This stops the time tracker service.
  • systemctl disable timetracker: This prevents the service from starting on boot.

By creating and managing a systemd service, you can automate tasks and ensure they run reliably in the background on your Linux system.

Tracking logs for your systemd services can be done using journalctl, a utility that allows you to query and display messages from the systemd journal.

Tracking logs using journalctl

To view the logs for a specific service, you use the -u (or --unit) option followed by the name of the service. For our timetracker service, the command would be:

journalctl -u timetracker

This will display all the logs from the timetracker service starting from the oldest. If you want to see the newest entries last, you can add the -e (or --pager-end) option:

journalctl -e -u timetracker

In addition, if you want to follow the logs in real-time, you can use the -f (or --follow) option:

journalctl -f -u timetracker

If you’re only interested in entries since the last boot, you can use the -b (or --boot) option:

journalctl -b -u timetracker

journalctl provides many more options for filtering and displaying log entries. For more information, you can refer to the man page (man journalctl).

Remember, journalctl provides a centralized method to access and manage logs from different systemd units. It's a powerful tool for troubleshooting and system auditing. With journalctl in your Linux toolkit, you can effectively manage and track logs for your systemd services.

Conclusion

Understanding and creating daemon services is a fundamental aspect of Linux system administration. They automate and manage key system tasks that run in the background, enhancing the efficiency and performance of the system.

Through this guide, we have taken a very brief view of the world of daemon services using systemd. We’ve explored different init systems, their evolution, and why systemd has emerged as the most widely used init system in modern Linux distributions. We also ventured into the anatomy of a systemd service file, creating our own sample service along the way.

Remember, practice is the key to mastering any skill, and Linux system administration is no different. Create different services, experiment with systemd’s advanced features, and don’t shy away from tackling more complex tasks. Your persistence will be rewarded with a firm grasp over the Linux ecosystem, setting you up for success in your Linux journey.

References

--

--