Managing Services in Linux
local graph
Chapter 5 — Managing Services in Linux
Section titled “Chapter 5 — Managing Services in Linux”In this chapter, we’re going to explain services (programs running in the background as daemons) in more depth. We’re going to explain init scripts and systemd units. We are also going to cover Alpine Linux rc commands that manage services.
The chapter covers the following topics:
- Understanding Linux services in detail
- A few words about Upstart, an alternative
Technical requirements
Section titled “Technical requirements”For this chapter, you will need a Linux system at hand where you can execute privileged commands, either using sudo or jumping straight to the root account (although we particularly recommend the first one). You’ll also need a Linux text editor of your choice that will produce pure text files. If you are going to edit on a Windows system, use a text editor that enables you to save Unix files. We recommend editing in the command line with one of your favorite command-line text editors: vim, emacs, joe, nano, or whatever suits you.
Understanding Linux services in detail
Section titled “Understanding Linux services in detail”Unless you are running some kind of low-level embedded device on your desktop—and we strongly doubt it—your operating system manages a multitude of tasks to create a comfortable and productive environment for you. Be it Mac OS X, Linux, Windows, or FreeBSD, they all run a multitude of background programs that together provide a useful system. The same goes for server flavors of those operating systems. A background program or background process (in Unix and Linux called, fluffily, a daemon) means a program that is not attached to any input (keyboard, mouse, etc.) or output (monitor, terminal, etc.). This way, they can start working even when no one is logged in to the system and keep working when the user logs out. They can also run under the privileges of a user who can never log in to the system, making their execution much safer.
The number of services running on your Linux system will, in large part, depend on the distribution and, in even larger part, on the system’s purpose.
The history of Linux service management
Section titled “The history of Linux service management”As you can probably imagine, the task of managing the system services—the programs required to run so that your computer is usable to you—is not a trivial one. The software that runs them must be stable and robust. This, and the fact that the system is expected to start rarely, especially on servers, made the Linux-adopted solution survive for decades. The increasing need to start services in parallel (through the emergence and widespread use of many threaded CPUs) and more intelligently gave way to several implementations of the new init system, which we will cover next.
systemd
Section titled “systemd”systemd is a service manager for Linux that is able to manage services that start with the operating system. It replaces traditional init scripts. It is responsible for starting and stopping system services, managing system state, and logging system events. It has become the default init system for many popular Linux distributions, including CentOS, Fedora Linux, Red Hat Enterprise Linux (RHEL), and Ubuntu Linux.
This service manager is responsible for controlling the initialization of the system itself (services required for the Linux OS), starting and stopping system services, and managing system resources. It provides another way of managing services and other system components, and it allows system administrators to configure and customize the behavior of their systems in a more standardized way than with System V (SysV) init.
One of the key features of systemd is its ability to start services in parallel, which can significantly reduce the boot time of a system. It also includes a number of tools for managing and monitoring system services.
Another thing systemd is praised for is the uniformity of service configurations it has finally brought to the Linux world. In every Linux distribution, the systemd configuration files are delivered to the same path; they look the same. There are, however, still some differences depending on the path binaries are being installed to. systemd is also better at knowing whether a process is running, making it more difficult to end up in a situation where we can’t start a process because of stale files.
One of the major advantages of systemd is its awareness of dependencies. The service (running program under systemd control) configuration contains information about all the other services it depends on and can also point to services that depend on it. What’s more, the service can inform systemd about which targets it requires to run: if your service needs the network to be up and running, you can put this information into the configuration, and systemd will ensure your daemon will be brought up only after the network is properly configured.
The following is a list of some of the tools and utilities that are provided as part of systemd:
systemd: This is the main system and service manager. It is the main program that controls the initialization and management of services and other system components.systemctl: This is the command-line utility for managing system services and other system components. It can be used to start, stop, restart, enable, and disable services, as well as to view the status of services and other system components.journalctl: This is used for viewing and manipulating the system log, which is managed bysystemd. It can be used to view log messages, filter log messages based on various criteria, and export log data to a file.coredumpctl: This is a utility, as the name suggests, that helps retrieve core dumps fromsystemd’s journal.systemd-analyze: This can be used for analyzing the boot performance of a system. It measures the time it takes for a system to boot, as well as the time it takes to identify potential bottlenecks and performance issues.systemd-cgls: This is a command-line utility for viewing the control group hierarchy on a system. Control groups, or cgroups, are used bysystemdto manage system resources and to isolate processes from one another.systemd-delta: This is a command-line utility for analyzing the differences between the default configuration files provided bysystemdand any local modifications made to these files.systemd-detect-virt: This is a command-line utility for detecting the virtualization environment in which a system is running. It can be used to determine whether a system is running in a virtual machine (VM), a container, or on bare metal.systemd-inhibit: This is a command-line utility for preventing certain system actions, such as suspending or shutting down the system, from being performed.systemd-nspawn: This is a command-line utility for running processes in lightweight containers. It can be used to create and manage containers, as well as to execute processes within containers.
This is just a list of more common tools and utilities that are provided as part of systemd. There are many more, but we will not cover them here.
Targets
Section titled “Targets”In systemd, a target is a specific state that the system can be in, and it is represented by a symbolic name. Targets are used to define the high-level behavior of the system, and they are typically used to group together a set of related services and other system components.
For example, multi-user.target is a target that represents a system that is ready to provide multi-user access, with networking and other services enabled; graphical.target is a target that represents a system that is ready to display a graphical login screen, with a graphical desktop environment and related services enabled.
Targets are typically defined in unit files, which are configuration files that describe the properties and behavior of system components. When a target is activated, systemd will start all of the services and other system components that are associated with that target.
systemd includes a number of predefined targets that cover a wide range of common system states, and administrators can also define custom targets to suit the specific needs of their systems. Targets can be activated using the systemctl command, or by modifying the default target that is set when the system boots.
Here are some examples of predefined systemd targets:
poweroff.target: Represents a system that is shutting down or powered offrescue.target: Represents a system that is running in rescue mode, with minimal services enabledmulti-user.target: Represents a system that is ready to provide multi-user access, with networking and other services enabledgraphical.target: Represents a system that is ready to display a graphical login screen, with a graphical desktop environment and related services enabledreboot.target: Represents a system that is rebootingemergency.target: Represents a system that is running in emergency mode, with only the most essential services enabled
Here is an example of a systemd unit file that defines a custom target:
[Unit]Description=Unit File With Custom Target[Install]WantedBy=multi-user.targetThis unit file defines a target named Custom Target that is meant to be activated as part of multi-user.target. The WantedBy directive specifies that the target should be activated when multi-user.target is activated.
Here is another example of a systemd unit file named custom.target that defines a custom target:
[Unit]Description=My simple service[Install]WantedBy=multi-user.targetThe following is a unit file that is using our custom.target target:
[Service]ExecStart=/usr/local/bin/my-simple-serviceType=simple[Install]WantedBy=custom.targetThis unit file defines a target named Unit File With Custom Target and a service named My simple service. The ExecStart directive specifies the command that should be used to start the service, and the Type directive specifies the type of service. The WantedBy directive in the [Install] section of the service unit specifies that the service should be activated when custom.target is activated.
Now, as we have touched upon unit files a bit, let’s dig into them deeper and see what is possible with them.
Unit files
Section titled “Unit files”Unit files are usually stored in the /lib/systemd/ system directory of Linux OS filesystems. No files in this directory should be altered in any way since they will be replaced by files contained in packages when a service is upgraded using a packet manager.
Instead, to modify a unit file of a specific service, create your customized unit file inside the /etc/systemd/system directory. Files in this etc directory will take precedence over the default location.
systemd is able to provide unit activation using the following:
- Dependency: It will start a unit simply by using a pre-built dependency tree handled by
systemd. At its simplest, you will need to add a dependency withmulti-user.targetor withnetwork.targetif your service is using networking. - Drop-in unit files: You can easily extend the default unit file by providing a snippet that will override a part of the default unit file (for example, change daemon execution options). Those are the files you’d place inside the
/etc/systemd/systemdirectory. - Templates: You can also define template unit files. Those special units can be used to create multiple instances of the same general unit.
- Security features: You can specify read-only access or deny access to a part of the filesystem, assign
private/tmpor network access, and limit kernel capabilities. - Path: You can start a unit based on activity on or the availability of a file or directory in the filesystem.
- Socket: This a special type of file in the Linux operating system that enables communication between two processes. Using this feature, you can delay starting a service until the associated socket is accessed. You can also create a unit file that simply creates a socket early in a boot process and a separate unit file that uses this socket.
- Bus: You can activate a unit by using the bus interface provided by D-Bus. D-Bus is simply a message bus used for inter-process communication (IPC), most commonly used in GUIs such as GNOME or KDE.
- Device: You can also start a unit at the availability of hardware (the
devfile, located in the/devdirectory). This will leverage a mechanism known asudev, which is a Linux subsystem that supplies device events.
Once you’ve started a service, you will probably want to check whether it’s up and healthy by taking a look at the log files. This job is taken care of by journald.
Logging
Section titled “Logging”Every service managed by systemd sends its logs to journald —a special part of systemd. There is a special command-line tool for managing those logs: journalctl. In its simplest form, running a journalctl command will simply output all system logs, with the newest ones being at the top. While the format of the logs is similar to syslog —the traditional tool for gathering logs on Linux— journald captures more data. It collects data from the boot process, kernel logs, and more.
The boot logs are transient by default. This means they are not saved between system reboots. There is, however, a possibility to record them permanently. There are two ways to do it, as follows:
- Create a special directory. When
journalddetects it during system boot, it will save logs there:sudo mkdir -p /var/log/journal. - Edit the
journaldconfiguration file and enable persistent boot logs. Open the/etc/systemd/journald.conffile with your favorite editor and, in the[Journal]section, edit theStorageoption to look like this:[Journal]Storage=persistent
journald is capable of filtering logs by service by the use of the -u service.name option—that is, journalctl -u httpd.service will only print logs from the httpd daemon. There’s a possibility of printing logs from a given timeframe, printing from more than one service, searching logs by process ID (PID), and more. As usual, we recommend referring to the man page—use the man journalctl command for this.
In this section, we have covered the most often used services software in the Linux world— systemd. In the next section, we are going to look at OpenRC—a system used in Alpine Linux, the Linux distribution of choice for containers in the cloud.
OpenRC
Section titled “OpenRC”Alpine Linux uses another system for managing system services called OpenRC. OpenRC is a dependency-based init system originally developed for the use of Gentoo Linux. It is designed to be lightweight, simple, and easy to maintain. OpenRC uses plain text configuration files, which makes it easy to customize and configure. It is also easy to extend with custom scripts and programs. OpenRC is flexible and can be used on a wide variety of systems, from embedded devices to servers.
The following are examples of how OpenRC is used in Alpine Linux:
- Starting and stopping system services: OpenRC is used to manage system services such as networking,
ssh, andcron. You can use therc-servicecommand to start, stop, or check the status of a service. For example, to start thesshservice, you can runrc-servicessh start. - Customizing system initialization and shutdown: OpenRC allows you to write custom scripts to customize the behavior of your system during startup or shutdown. These scripts are executed at specific points in the boot process and can be used to set up custom configurations or perform other tasks.
- Managing system runlevels: OpenRC uses runlevels to define the system’s behavior. You can use the
rc-updatecommand to add or remove services from different runlevels. For example, to make a service start at boot, you can runrc-update add <service> boot.
To start a service, use the following rc-service command:
admin@myhome:~$ rc-service <service> startTo stop a service, use the following rc-service command:
admin@myhome:~$ rc-service <service> stopTo check the status of a service, use the following rc-service command:
admin@myhome:~$ rc-service <service> statusTo enable a service to start at boot, use the following rc-update command:
admin@myhome:~$ rc-update add <service> defaultTo disable a service from starting at boot, use the following rc-update command:
admin@myhome:~$ rc-update del <service> defaultDefault in this context means a default runlevel of the Alpine Linux system. Runlevels in general are used to define the system’s behavior. There are several predefined runlevels common to most Linux distributions, each of which corresponds to a specific set of services that are started or stopped.
In Alpine Linux, these are the default runlevels:
default: This is the default runlevel and is used when the system is booted normally. Services that are started in this runlevel include networking, SSH, and system logging.boot: This runlevel is used when the system is booting. Services that are started in this runlevel include the system console, the system clock, and the kernel.single: This runlevel is used when the system is booted into single-user mode. Only a minimal set of services is started in this runlevel, including the system console and the system clock.shutdown: This runlevel is used when the system is shutting down. Services that are stopped in this runlevel include networking, SSH, and system logging.
OpenRC uses a very similar way of defining service actions to SysV init we mentioned earlier in this chapter. Commands such as start, stop, restart, and status are defined in a Bash script. Here is a basic example of a service:
# Name of the servicename="exampleservice"# Description of the servicedescription="This is my example service"# Start commandstart() { # Add your start commands}# Stop commandstop() { # Add your stop command here}# Restart commandrestart() { stop start}To create a new service, you can copy this file to a new file and modify the name, description, start, stop, and restart functions as needed. The start function should contain the command to start the service, the stop function should contain the command to stop the service, and the restart function should stop and start the service. Those can be the same as for SysV init.
In OpenRC, init scripts are typically stored in the /etc/init.d directory. These are scripts that are used to start and stop services and manage the system’s runlevels.
To create a new init script for OpenRC, you can create a new file in the /etc/init.d directory and make it executable.
Once you have created your init script, you can use the rc-update command to add it to the default runlevel, which will cause the service to start at boot. For example, to add the exampleservice service to the default runlevel, you can run the following command:
admin@myhome:~$ rc-update add exampleservice defaultIn most cases, we’ll be using Alpine Linux in a Docker environment where there’s little use for OpenRC, but it’s still useful to know for some edge-case usage. We will look at Docker in more detail in Chapter 8 and Chapter 9.
In this section, we have looked at OpenRC, software that controls system services in Alpine Linux. In the next section, we are going to introduce, very shortly, an outdated form of SysV init, which may come up with older or minimal Linux distributions.
SysV init
Section titled “SysV init”As previously mentioned, the init process is the most important continuously running process in the system. It’s responsible for starting system services when the system boots up or when an administrator requests it, and stopping system services when the system is shutting down or when requested, all in the proper order. It’s also responsible for restarting services on request. Since init will execute code on behalf of the root user, it is imperative that it’s well tested for stability and security risks.
One of the charming properties of the old init system was its simplicity. The starting, stopping, and restarting of a service was managed by a script—one that had to be written by either the application author, the distribution package owner for this application, or the system administrator—if the service was not installed from packages. The scripts were simple and easy to understand, write, and debug.
The more the complexity of software grew, however, the more the old init system showed its age. Starting up a simple service was okay. Starting up an application consisting of several programs grew more difficult, especially as the dependencies between them became more important. init lacks observation of dependencies of startup of the services it takes care of.
Another place where the old init system became more and more unfit for modern systems was serial startup: it was unable to start services in parallel, thus negating modern multicore CPU gains. The time was nigh to look for a system more fit to the new times.
A typical init system consists of several components, as follows:
- A
/etc/init.dor/etc/rc.d/init.ddirectory that contains start/stop scripts. - A
/etc/inittabfile that defines runlevels and sets up a default one. - A
/etc/rcX.ddirectory that contains all the scripts for services that should be started or stopped in the runlevelX, whereXis a number from0(zero) to6. We will get to the details in the next paragraph.
The /etc/init.d/ directory contains shell scripts responsible for starting, stopping, and restarting services. The script accepts a single argument of either start, stop, or restart. Each argument passed to the script executes a proper function (usually named the same as the argument: start, stop, or restart), and the function runs a set of steps to properly start, stop, or restart the given service. The kind of final state of the start process that the system ends up in is called a runlevel. The runlevel determines whether services are being started or stopped and which of them are being started if this is the course of action.
To determine the type of action to call, a link to the script would be created in the directory related to the runlevel in question.
Let’s assume we want the system to end up in runlevel 3. If we want our service to be started in this runlevel, we would create a link to the /etc/rc.d/my_service script pointing to the /etc/rc3.d/ directory. The name of the link determines the type of action and the order. So, if we wanted the service to be started after numbers 01 - 49, we would call it /etc/rc.3/S50my_service. The letter S tells the init system to start the service, and the number 50 tells it to start it after all services with lower numbers have been started. Please note that the numbering is more of a framework. It is not guaranteed that there are scripts with all other numbers prior to 50. The same goes for stopping services. After determining which runlevel is the default for stopping the system (usually 0), a proper symlink is created for the service script.
The major problem with the preceding framework is that it’s totally unaware of dependencies. The only way to ensure that the services on which your daemon depends are running is to script it around in your start function. In the case of more complex applications comprising many services, this may lead to bigger start/stop scripts.
Another issue with init scripts being raised by admins and developers was that there are multiple standards on how to write them and multiple different tools around init scripts. Basically, every major Linux distribution had its own way of writing those scripts and its own library of helper functions. Let’s consider an init script starting the same My Service service on Slackware Linux and Debian/GNU Linux. This is also where the introductory chapter on writing shell scripts comes in handy.
In both cases, Slackware and Debian, we are going to cut some original content out for brevity, leaving only the most important parts. Do not worry as both distributions deliver wholly commented example scripts.
The following init script will work in a Slackware Linux environment. The script starts with a header where we declare the name of the service and some important paths:
#!/bin/bash## my_service Startup script for the My Service daemon## chkconfig: 2345 99 01# description: My Service is a custom daemon that performs some important functions.# Source function library.. /etc/rc.d/init.d/functions# Set the service name.SERVICE_NAME=my_service# Set the path to the service binary.SERVICE_BINARY=/usr/local/bin/my_service# Set the path to the service configuration file.CONFIG_FILE=/etc/my_service/my_service.conf# Set the user that the service should run as.SERVICE_USER=my_service# Set the process ID file.PIDFILE=/var/run/my_service.pid# Set the log file.LOGFILE=/var/log/my_service.logThe good thing is that an example script delivered with Slackware is very well commented. We have to declare a path to the binary for the daemon. We also have to declare the user and group that the service will run as, effectively deciding filesystem permissions for it.
The next section defines all important actions for the service: start, stop, and restart. There are usually a few others, but we have cut them out for brevity:
start() { echo -n "Starting $SERVICE_NAME: " # Check if the service is already running. if [ -f $PIDFILE ]; then echo "already running" return 1 fi # Start the service as the specified user and group. daemon --user $SERVICE_USER --group $SERVICE_GROUP $SERVICE_BINARY -c $CONFIG_FILE -l $LOGFILE -p $PIDFILE # Write a lock file to indicate that the service is running. touch $LOCKFILE echo "done"}The start function checks whether the service is running utilizing the pid file. The pid file is a text file that contains the PID of the service. It gives information about both the main process of the service and its status. There is a caveat, however. It is possible that the service isn’t running anymore and the pid file still exists. That would prevent the start function from actually starting the service.
After the check determines that the pid file doesn’t exist, which means that the service is not running, a special tool called daemon is used to start the process with user and group permissions, pointing to a configuration file, log file, and pid file locations.
The function communicates its actions using the bash echo command, which prints the given text. In case of automatic execution, the output of the echo command will be logged to system logs depending on the logging daemon configuration:
stop() { echo -n "Stopping $SERVICE_NAME: " # Check if the service is running. if [ ! -f $PIDFILE ]; then echo "not running" return 1 fi # Stop the service. killproc -p $PIDFILE $SERVICE_BINARY # Remove the lock file. rm -f $LOCKFILE # Remove the PID file. rm -f $PIDFILE echo "done"}Again, the stop function checks whether the service is running using the pid file. The probability of the service running without a proper pid file is almost nonexistent. After the check is done, a special command called killproc is used to terminate the process. In the final part of the function, the script does some housekeeping tasks, cleaning the pid file and the lock file:
restart() { stop start}The restart function is very simple. It reuses the already defined start and stop functions to do exactly what it says: restart the service. This is often useful if the service configuration requires the binary to be loaded again:
case "$1" in start) start ;; stop) stop ;; restart) restart ;; *) echo "Usage: $0 {start|stop|restart|uninstall}"esacThe final part of the script evaluates the action we want to take—start, stop, or restart the service—and calls the proper function. If we ask it to do something it doesn’t recognize, the script will print out usage instructions.
The following script, however, is intended for a Debian Linux environment:
#!/bin/bash## my_service Startup script for the My Service daemon## chkconfig: 2345 99 01# description: My Service is a custom daemon that performs some important functions.# Source function library.. /lib/lsb/init-functions# Set the service name.SERVICE_NAME=my_service# Set the path to the service binary.SERVICE_BINARY=/usr/local/bin/my_service# Set the path to the service configuration file.CONFIG_FILE=/etc/my_service/my_service.conf# Set the user that the service should run as.SERVICE_USER=my_service# Set the group that the service should run as.SERVICE_GROUP=my_serviceAgain, the script starts with a header section that defines paths to be later used in the start and stop sections. Normally there are more lines, but we’ve cut them out for brevity, again:
start() { log_daemon_msg "Starting $SERVICE_NAME" # Check if the service is already running. if [ -f $PIDFILE ]; then log_failure_msg "$SERVICE_NAME is already running" log_end_msg 1 return 1 fi # Start the service as the specified user and group. start-stop-daemon --start --background --user $SERVICE_USER --group $SERVICE_GROUP --make-pidfile --pidfile $PIDFILE --startas $SERVICE_BINARY -- -c $CONFIG_FILE -l $LOGFILE # Write a lock file to indicate that the service is running. touch $LOCKFILE log_end_msg 0}The start function looks similar to the one from the Slackware version. You’ll notice some subtle differences, however, as follows:
- The
start-stop-daemonhelper function is being used here to manage the running service instead ofdaemonandkillproc - There are specialized functions for logging instead of simple echo:
log_daemon_msg,log_failure_msg, andlog_end_msg - The
start-stop-daemonfunction accepts special flags to determine the action (startandstop) as well as detaching the program from the terminal, making it effectively a system service (--background), as seen here:
stop() { log_daemon_msg "Stopping $SERVICE_NAME" # Check if the service is running. if [ ! -f $PIDFILE ]; then log_failure_msg "$SERVICE_NAME is not running" log_end_msg 1 return 1 fi # Stop the service. start-stop-daemon --stop --pidfile $PIDFILE # Remove the lock file. rm -f $LOCKFILE # Remove the PID file. rm -f $PIDFILE log_end_msg 0}The stop function is pretty similar to the stop function from Slackware, with similar differences to those the start function had.
The rest of the script containing the restart function and the task evaluation is not that interesting, and we’ve cut it out.
As you probably still remember from the section about systemd, it solves some of those problems. SysV is not seen too often in modern systems, so you will most commonly need to deal with systemd instead.
There is, however, another replacement for SysV init called Upstart.
A few words about Upstart, an alternative
Section titled “A few words about Upstart, an alternative”Upstart is an event-based replacement for the traditional SysV init system used to manage and control services and daemons on a system. Upstart was introduced in Ubuntu 6.10 and later versions and is designed to improve boot time, simplify system configuration, and provide more flexibility in managing system services. It has now been largely replaced by systemd in most Linux distributions.
Upstart is used to manage the initialization process of the system and to start, stop, and supervise tasks and services. It is designed to be more flexible and efficient than the traditional init daemon and to provide more information about the status of tasks and services.
All that can be managed by systemd and/or cron has become an industry standard, so if you don’t have a good reason for using those or already have a system using Upstart, we discourage you from using it as a default.
Summary
Section titled “Summary”In this chapter, we covered system services—or daemons in the Unix and Linux world—and the software most often used to manage them. We explained what those are, how to inspect their state, and how to control them. In the next chapter, we are going to dive into Linux networking.