Member-only story
Systemd service error handling and automatic restarting
Would you like to run a program every time you start your Linux operating system? But you don’t want to run it manually every time? Then Systemd is the solution for you.
Systemd is an init system that has been used in many Linux distributions (Ubuntu, Debian, Mint, …) in recent years. A service is a process or a bunch of processes running in the background — it’s called daemon as well. Services are usually started at boot time.
In this short article I will show you:
- How to create your own systemd service.
- How to automatically restart the service if it fails.
- How to handle a situation where a service restart fails several times in a row.
I will demonstrate all these steps with a simple example so you can easily try it out and also adapt it for your own use. Let’s start with the first step.
Creating your own systemd service
First, let’s create a simple program that we would like to run as a service. You can use any executable, i.e. you can use any programming or scripting language. In this case, I will use Python. Let’s create a simple program that first writes a message that it has been executed to the log_prog.txt
file, and then writes the current time to it every ten seconds.
You can try to run this program just like any other Python program, by running python3 prog.py
.
How do we make this program to run as a service? We have to create an unit file. Minimal form would look as you can see below. Don’t forget to change the{username}
and the {your_work_dir}
.