Systemd Service File Example – How it Works

The service file manager in Linux - systemd - is configured using something called "unit files". Here's an example, and how it works.

On this page
  1. What You Need for this Example
  2. Creating the Python app
  3. Creating the Service Unit File
  4. Testing the Systemd Service Unit File
  5. Checking the Status of the Service
  6. Cleaning Up
  7. Conclusion

As far as tools go in the Linux world, systemd is a relatively recent development, as it has been the default service manager on all Linux flavors since around 2015. Some of the older guides on the Internet refer to “init.d”, which was the directory that older systems relied on for their shell scripts. The older system had several limitations, including a linear, non-event-driven start order and poor support for dependencies. Systemd changed all that. Now we use things called “unit files” to manage services, and the best way to explain this is to show a full systemd service file and use it.

#What You Need for this Example

In the example below, I will create a systemd service file example that runs a Python script to write a message to a file every five seconds. So you need to have Python installed on your Linux system before continuing. To verify if you have Python installed, run the following command:

Code
python3 --version

If you get an output, then all is well. If you don’t get a version number, then use the following commands:

Debian/Ubuntu

Code
sudo apt update
sudo apt install python3
sudo apt install python3-dev

Fedora-based distributions

Code
sudo dnf update
sudo dnf install python3

You might also want to install pip, but you don’t need it for this example.

#Creating the Python app

Once you’ve ensured that Python is installed, create a text file with the following content, and name it “app.py”:

Code
import time
import datetime
import os

# Get the directory of the script
script_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(script_dir, "simple_app_output.txt")

while True:
    with open(output_file, "a") as f:
        f.write(f"[{datetime.datetime.now()}] Simple Python app is running and writing to file!\n")
    time.sleep(5) # Write every 5 seconds

Now make the app.py script executable – this might not be necessary for Python apps, but it’s still a good practice to remember:

Code
sudo chmod +x app.py

Testing the Python Script

Let’s see if the above script works. Type the following into your command line in the directory containing the app.py file:

Code
Python3 app.py

This should make the cursor stall on the next line as it waits for your interrupt. After waiting for, say, 15 seconds, press Ctrl+C. If everything worked, there should now be a file called “simple_app_output.txt” in the same location containing some lines, as shown here:

If this is the output you see, then everything is working as expected.

#Creating the Service Unit File

Linux places the non-system-related service files in the following location:

/etc/systemd/system/

For example, if you list the contents of the directory, this is what you’ll see:

All the files here that end in “.service” are symlinks, which means they live in other locations. We can follow the same procedure, but there’s no need. Let’s create a file in this directory called my_simple_app.service, containing the following code:

Code
[Unit]
Description=My Simple Python Application
After=network.target

[Service]
User=ubuntu
WorkingDirectory=/home/ubuntu/
ExecStart=/usr/bin/python3 /home/ubuntu/app.py
Restart=always
RestartSec=5s
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target

In the above, replace “ubuntu” with your username, assuming your home directory is in “/home/yourusername/.

Ok, now we have all the pieces in place. Let’s use this unit file and see what happens!

#Testing the Systemd Service Unit File

To test our service, we need to carry out the following tasks:

  1. Reload systemd so that it finds our new service file
  2. Enable the service for auto-start on boot
  3. Start the service immediately

The first step is to make systemd aware that our new service file is sitting in its directory. To do this, we type:

Code
sudo systemctl daemon-reload

This will take a moment to execute, and then we make it so that our service starts whenever the server boots up next, so that we don’t have to start it automatically:

Code
sudo systemctl enable my_simple_app.service

The above command also creates a new symbolic link. This link will be placed in an appropriate location for the service, considering its target and other parameters. Next, we want to start the service. We do this with:

Code
sudo systemctl start my_python_app.service

If you want, you can combine the last two commands with:

Code
sudo systemctl enable --now my_python_app.service

Here’s how it looks when you execute all these commands:

You can see that when we enable the service, it creates a symlink in the following location:

Code
/etc/systemd/system/multi-user.target.wants/my_simple_all.service

This is a common location for non-graphical services, so everything is proceeding as expected.

#Checking the Status of the Service

Now that we’ve created and enabled the service, let’s see if it’s actually working. After we’ve enabled and started the service, and we’ve waited a while, we can open the “simple_app_output.txt” file to which our service writes, and see if it’s getting filled up. You should see something like this:

As you can see, the service is running as expected. The timestamps indicate that the output is being generated once every five seconds, just as we instructed. So we know that it’s working!

We can also get comprehensive information about what’s happening with the service via the journal. If you recall the following two lines in the service file:

Code
systemctl status my_python_app.service

This will give the following output:

The above output tells you everything you need to know about the service. You can see that it has a link to the base path file (not just the symlink), and it tells you that the service is enabled (starting on boot), and that it’s currently running. It also gives you information about the resources it’s used so far in terms of CPU and memory. At the end, you can even see the command that was used to start it.

If you’re trying to see what’s wrong with a misbehaving process, checking its status is a great starting point.

Seeing the Journal Logs

A cool feature of Linux systems after 2011 is the “journal” system, to which all events are logged for services. Unlike log files, these journal entries are stored in a centralized place in binary form, instead of text. This allows them to be stored very efficiently, and we need to use a special command to access the journal because a text editor won’t work.

You’ve surely been frustrated in the past by the dozens of log files for applications stored in a multitude of locations all over the server. With the journal, you don’t need to wonder anymore.

If you want to see your application logs in the journal, you just need to use the following command:

Code
journalctl -u my_python_app.service -f

This is because we included the following two lines in the service unit file:

Code
StandardOutput=journal
StandardError=journal

These instructions tell the service to log outputs and errors in the journal. Actually, they get sent to the journal by default, but it’s nice to include them explicitly. The output of the above command is this:

Nothing much to report, but it’s better than checking a log file!

#Cleaning Up

Once you’re done with the service, you can use the following commands to clean up.

Stop the service:

sudo systemctl stop my_python_app.service

Disable the service:

Code
sudo systemctl disable my_python_app.service

Delete the service file:

Code
sudo rm /etc/systemd/system/my_python_app.service

Reload the service daemon to reflect the removal of the unit file:

Code
sudo systemctl daemon-reload

All these commands will remove every trace of the service file we just created on the system:

And you’re done!

#Conclusion

As you can see, creating a service in Linux is easy, using service files. As with everything in Linux, it’s entirely file-based, and with just a few commands, you can convert a script running in the background into a full-fledged service and monitor it.

Photo of Bhagwad Park
Written by

Bhagwad Park

Bhagwad Park writes for the NameHero blog.

More from Bhagwad →