1. Introduction
There are many times we want an application to continue running once it is started. We could consider a cron job or script, but there is an easier and more reliable solution, systemd.
systemd is an initializer tool that brings all the Linux configured applications and processes up after the booting process. In this tutorial, we’ll look at how to make our application, or script, a systemd service.
2. Example Application
First, let’s choose an application which we’ll use to create a service. Python2 provides a simple HTTP server module that can run HTTP Server in a single line:
python -m SimpleHTTPServer
We can check that the server is up and running by navigating to http://localhost:8000 in a browser.
3. Creating Service
Now that we have our application ready, we need to create a systemd service definition file. Let’s create a service definition file at /etc/systemd/system/simplehttpserver.service with the following contents:
[Unit]
Description=Simple Http Server
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
Restart=always
RestartSec=1
User=myusr
ExecStart=python -m SimpleHTTPServer
[Install]
WantedBy=multi-user.target
To configure the application to run, we provided the ExecStart=
Apart from the above directives, we need to configure some advance directives to make our service resilient to failures.
We added the After directive so systemd will take care of starting the services listed before starting our current service. Since our service needs the network service, based on our configuration, systemd will bring it up before starting our service.
Since, by default, systemd does not restart the service on exit, we included the Restart directive to enable this behavior by setting it to always.
By default, the systemd attempts a restart after 100ms. We can specify the number of seconds to wait before attempting a restart by setting the RestartSec directive.
When we configure Restart=always, systemd gives up restarting the service if it fails to start more than 5 times within a 10 second interval. Therefore, if we want the service to restart automatically, there are some additional options we can use:
- Set RestartSec to be 3 or more. Then systemd will never be able to reach restart 5 times in a 10-second interval.
- Set StartLimitIntervalSec=0. Also, it is recommended to keep the RestartSec directive to be 1 or more to avoid putting too much stress on the server.
4. Running the Service
Now that we’ve configured our application as a service in the last section. Let’s start our service with the following command:
systemctl start simplehttpserver
To check our service status any time we can use the systemctl status command as follows:
systemctl status simplehttpserver
To enable our service to auto-start on boot, we use the enable argument:
systemctl enable simplehttpserver
5. Conclusion
In this tutorial, we have learned how to create the systemd service for long-running applications with a simple web server example.