I wanted to write a systemd service file for a daemon I wanted started automatically at boot on my Raspberry Pi running Debian Jessie.
This used to be a lot simpler in the old hardcore Unix days. Well, no, actually, it’s simpler now. But figuring out how to do it was anything but simple and took me the better part of a day. Maybe I’m just bad at google, but I couldn’t find a simple “just do THIS” recipe; all I could find was hopelessly detailed and complex descriptions of systemd stuff that exceeded my newbie level of understanding and exceeded my geezer level of interest in reading lots of stuff.
So, here, in the hope that someone else will find this via google someday and find it useful, is how to do it. Or, at least, one way that works.
Step 1: Make a clown.service file
Assume you want /usr/local/bin/clown started at boot time, with the arguments: -name bozo
Make a file in /lib/systemd/system, called “clown.service”. Whatever you call this file (the “clown” part in this example) becomes the name of the service. Here’s what you need in the file:
[Unit] Description=Clown server for jessie After=network.target [Service] Type=simple ExecStart=/usr/local/bin/clown -name bozo Restart=always [Install] WantedBy=multi-user.target
The key things you may need to change (besides the obvious command name and arguments) are the Type and the Restart entries.
Type=simple says your program doesn’t fork (i.e., needs to be “daemonized” by systemd). There are other options; look these up in the systemd documentation yourself if you have a more complex scenario.
Restart=always says that any time the program exits it should be started right back up again. This is exactly what I needed as my program isn’t supposed to die, but if it does I want it started again. The systemd program implements throttles on how often this happens in case things have gone haywire.
[Install] section tells it to run the service whenever the system is in multi-user mode, and the
After= part up top tells it not to start the service until the network is up.
Step 2: Tell systemd about this file
It’s not enough to just drop this file into the /lib/systemd/system directory. You also need to execute this command (just once, ever, for a new service file):
% sudo systemctl enable clown.service
You need to do that as root (hence the sudo, or just be root). You’ll get a message about it creating some symbolic links, which is good.
And … that’s it. Reboot and pray! Try looking in /var/log/daemon.log if you encounter any problems.