Using systemd service for performing jobs gives a great flexibility and options for performing the said job. In this article we will show you how to make a simple systemd service that starts up a http server in the specified port.

First we need script/command to start our simple http server. Instead of creating a separate script for doing so, We’ll use python’s command line to create the server.

python -m http.server 8000

This command serves files from the directory where the command was executed from at port 8000.

Now let’s create a file that defines our service with .service at the end of the filename.

Now, place the file at /etc/systemd/system. This is where the user defined service files should go.

Placing the file in required location isn’t enough, we have to tell systemctl that there is some change it needs to look at. So we’ll reload systemctl. Or we can also reboot the system completely.

sudo systemctl daemon-reload

Now we can start our service as:

sudo systemctl start new_daemon

To check the status of our service:

sudo systemctl status new_daemon

If you see something like this, you’re good.

To have this service started by default on bootup, enable it:

sudo systemctl enable new_daemon

You can stop or disable the service too:

sudo systemctl stop new_daemon
sudo systemctl disable new_daemon

Now go to localhost:8005 to confirm that the http server is up and running. You should see the directory listing of working directory specified in new_daemon.service file.

See manual page of systemd.service for further information on possibilities to customize you service.

Going further

On our new_daemon.service file, we specified Restart=on-failure. So when the python process that keeps the server running exits with failure, the service will restart it automatically. Noice, isn’t it? Let’s kill that process manually and see what happens.

Let’s kill process with pid=1553 with:

sudo kill -9 1553

Now if we check for the status of our service, we see that it is up and running again. It automatically starts another python process to keep the server up.

And another amazing thing is that we also get logs for our service by journalctl.

We can see that our main process was killed and then it was automatically started.

That’s all for today, if you have any questions, don’t hesitate to reach us.