Create linux services the easy way

Linux used to struggle with managing services because of the simple design of SysV init. It was not really a service configuration system, just a folder structure that decided when processes were started. You had to configure it all yourself. You needed to write a lot of boiler plate in your init scripts to get it going the right way, and mistakes were easy to make and hard to solve.

Not too long ago I ran into this where ulimits were correctly applied when a service started on reboot, but not when the service was restarted by the root user. When you discover why, it's evident, but until then, it feels like the system is just mocking you.

So, when systemd was introduced, it tried (and succeeded) to solve a lot of this by actually managing background services. Nowadays it does much much more, but let's focus on the service management. You can convert any process into your own service in under a minute. Easy for any Linux system, including Raspberry Pi's running Raspbian, or any other Linux flavour.

We start by identifying what needs to start. If it's just a simple process /usr/bin/myprocess that you start from the command line, your systemd config file would look like this:

[Unit]
Description=My fancy description
After=network.target

[Service]
Type=simple (or forking, if the prompt comes back after starting it manually)
ExecStart=/usr/bin/myprocess
Restart=on-failure

[Install]
WantedBy=multi-user.target

You can edit your config file with nano by issuing the command sudo nano /etc/systemd/system/myname.service. When done, just enable the service by issuing the commands:

  • To reload the systemd configuration: sudo systemctl daemon-reload (or reboot).
  • To enable the service for startup on reboot: sudo systemctl enable myname

This article is my 2nd oldest. It is 284 words long