As a Linux system administrator, it’s crucial to have a good understanding of systemd, which is the system and service manager in modern Linux distributions. In this article, we will explore how to create a Linux service with systemd.
Systemd is responsible for managing system services, which are programs that run in the background and provide a specific function, such as a web server, database server, or email server. Systemd makes it easy to start, stop, restart, and manage services.
What is systemd?
systemd is a system and service manager for Linux operating systems. It was introduced as a replacement for the traditional SysVinit and other init systems. It is now the default init system for many popular Linux distributions, including Fedora, Debian, and Ubuntu.
systemd is responsible for the initialization and management of various system components and services, such as:
- Boot process: systemd starts and manages system services during the boot process, ensuring that everything is initialized in the correct order.
- Service supervision: systemd monitors and manages the lifecycle of system services, including starting, stopping, and restarting them as needed.
- Dependency management: systemd tracks dependencies between services, ensuring that they are started and stopped in the correct order.
- Logging: systemd includes the “journald” service, which provides centralized logging for system components.
- Resource management: systemd can manage system resources, such as CPU and memory usage, for individual services, ensuring that they don’t consume too much system resources.
systemd is designed to be compatible with existing SysVinit scripts, making it relatively easy to migrate existing systems to systemd. Its features and design make it more efficient, reliable, and scalable compared to traditional init systems.
Examples of Linux’s default systemd services
Here are three examples of popular systemd services on Ubuntu and their functions:
NetworkManager.service: NetworkManager is responsible for managing network connections on a Linux system. It detects and configures available network devices, manages wired and wireless connections, and handles network profiles for different locations. NetworkManager provides a user-friendly interface for managing networks and can be controlled through the command line, desktop applets, or graphical user interfaces.
To view the status of the NetworkManager.service on a Linux system using systemd, open a terminal and run the following command:
sudo systemctl status NetworkManager.service
This command will display information about the NetworkManager.service, including whether it is active, the current state, and any recent log entries related to the service.
udev.service: The udev service is responsible for managing device nodes in the /dev directory. It dynamically creates, removes, and maintains these device nodes when hardware devices are connected or disconnected from the system. The udev service ensures that devices are correctly recognized and accessible by the system and applications.
sudo systemctl status udev.service
cron.service: The cron service manages scheduled tasks on a Linux system. It is responsible for running tasks at specified intervals, such as hourly, daily, or weekly. Cron is commonly used for automating system maintenance tasks, such as rotating log files, updating databases, or running backups.
sudo systemctl status cron.service
These services are just a few examples of the many systemd services that Ubuntu uses to manage various system components and applications. You can view the status of these services or control them using the
Creating a Linux service with systemd
Creating a custom systemd service involves creating a service unit file, which defines the service and its behavior, and then enabling and starting the service using the systemctl command. Here’s a step-by-step guide to creating a simple systemd service:
Step 1: Create a script
Open a terminal: Press Ctrl + Alt + T to open a terminal window.
Create a new file: Use a text editor like nano to create a new file at the specified location:
sudo nano /usr/local/bin/Hello_FOSSLinux.sh
/usr/local/bin directory is a standard location for installing custom scripts and executables that are specific to the local system. By placing the
Hello_FOSSLinux.sh script in the
/usr/local/bin directory, you make it accessible to users on the system without needing to specify the full path when executing the script.
Enter the script content: Paste the following content into the text editor:
#!/bin/bash echo "Hello, FOSSLinux!"
Save and exit: Save the file by pressing Ctrl + O, then Enter. Exit the text editor by pressing Ctrl + X.
Step 2: Make the script executable
To make the script executable, run the following command:
sudo chmod +x /usr/local/bin/Hello_FOSSLinux.sh
Step 3: Create a systemd unit file
The next step is to create a systemd unit file that describes the service. Use a text editor like nano to create a new file at the specified location:
sudo nano /etc/systemd/system/FOSSLinux.service
Enter the unit file content: Paste the following content into the text editor:
[Unit] Description=FOSSLinux Service [Service] ExecStart=/usr/local/bin/Hello_FOSSLinux.sh [Install] WantedBy=multi-user.target
The Unit section provides a description of the service. The Service section defines how the service should be started, stopped, and restarted. The ExecStart directive specifies the command to start the service. The Install section specifies when the service should be started.
Save and exit: Save the file by pressing Ctrl + O, then Enter. Exit the text editor by pressing Ctrl + X.
Step 4: Reload systemd
Reload systemd: To make systemd aware of the new service, run:
sudo systemctl daemon-reload
Step 5: Start the service
After creating the systemd unit file, you can start the service using the following command:
systemctl start FOSSLinux
This will start the service and run the FOSSLinux.sh script. You may have to enter your password.
Step 6: Enable the service
If you want the service to start automatically when the system boots up, you can enable it using the following command:
systemctl enable FOSSLinux
This will create a symlink from the /etc/systemd/system/multi-user.target.wants/ directory to the service file.
Step 7: Check the status
To check the status of the service, you can use the following command:
systemctl status FOSSLinux
This will display the current status of the service, including whether it is running or not.
Congrats! You have just created your own systemd service!
Tips & Tricks
By following these tips and tricks, you can create more robust and efficient systemd services that are better equipped to handle different scenarios and ensure the smooth operation of your system.
Always use absolute paths in your systemd unit file to ensure that the service runs correctly: Systemd unit files should always use absolute paths for executable files and any other required files, such as configuration files or scripts. This is because systemd does not rely on the user’s environment variables, like $PATH, to locate files. Using absolute paths ensures that systemd can find and execute the correct files, regardless of the user or environment context in which the service is running.
Use the ExecReload directive in the Service section to specify the command to run when the service is reloaded: The ExecReload directive allows you to define a specific command that should be executed when the service is reloaded using the systemctl reload command. This is useful for services that can dynamically reload their configuration without needing a full restart. When defining the ExecReload directive, make sure to use an absolute path for the command or script you want to run. For example:
[Service] ExecStart=/path/to/executable ExecReload=/path/to/reload-script
Use the RestartSec directive in the Service section to specify the number of seconds to wait before restarting the service after a failure: The RestartSec directive allows you to define a delay (in seconds) before the service is restarted after a failure. This can be useful for services that require a specific amount of time to release resources or for preventing rapid restart loops that could cause high system load. By setting the RestartSec directive, you can control the restart behavior and avoid potential issues. For example:
[Service] ExecStart=/path/to/executable Restart=on-failure RestartSec=5
In this example, the service will restart after a 5-second delay if it exits with a failure (non-zero status).
By using these troubleshooting tips, you can identify and resolve issues with systemd services more effectively, ensuring the smooth operation of your system.
Check the syntax of your systemd unit file using the systemd-analyze verify command: Before starting or enabling a systemd service, it’s a good practice to check the syntax of the unit file to ensure there are no errors. You can use the systemd-analyze verify command to perform this check. For example, if your service is called my-custom-service.service, you can run:
systemd-analyze verify /etc/systemd/system/my-custom-service.service
This command will analyze the unit file and report any syntax errors, missing files, or other issues. Fix any reported issues before enabling and starting the service.
Check the logs for your service using the journalctl -u <service-name> command: If you’re experiencing issues with a systemd service, the first place to look for clues is the service’s log. You can use the journalctl command to view logs for a specific service. For example, to view logs for the my-custom-service.service, run:
journalctl -u my-custom-service.service
This command will display logs for the specified service, including any error messages, warnings, or other relevant information. You can use these logs to identify and fix issues with the service.
Use the systemd-analyze plot command to visualize the boot process and identify any issues: If you suspect that a service is causing issues during the boot process, the systemd-analyze plot command can help you visualize the boot process and identify potential problems. To generate a plot of the boot process, run:
systemd-analyze plot > boot-plot.svg
This command will create an SVG file called boot-plot.svg that contains a graphical representation of the boot process, including the start and stop times of each service. You can open this file in an SVG-compatible image viewer or web browser to analyze the boot process and identify any services that may be causing issues.
Creating a Linux service with systemd is a simple process that involves creating a script, creating a systemd unit file, starting the service, and enabling it to start automatically. By following the tips and tricks and troubleshooting tips provided in this article, you can create reliable and robust services that meet your system requirements. With systems, you have a powerful tool at your disposal for managing services on your Linux system. It’s essential to have a good understanding of systemd and its capabilities to effectively manage services on your Linux system.
In addition to creating and managing services, systemd also provides other useful features, such as logging, resource management, and network configuration. By leveraging these features, you can create more robust and scalable services that meet your system’s needs.
It’s important to keep in mind that systemd is a complex system, and there may be situations where troubleshooting is required. By following the troubleshooting tips provided in this article and leveraging resources such as the systemd documentation and online communities, you can resolve issues and ensure that your services are running smoothly.