Write a basic systemd service.
This will work on any distribution running systemd.
A working Linux install with systemd and root privileges.
- # - requires given linux commands to be executed with root privileges either directly as a root user or by use of
- $ - requires given linux commands to be executed as a regular non-privileged user
Systemd is nearly unavoidable. It has permiated so many aspects of the Linux ecosystem that it's necessary for any Linux admin to know at least the basics of how it works. One of the major selling points of systemd is the ease of writing service files. They aren't scripts. Instead, they're basic configuration files. While they can grow to be complex, they are usually very simple.
Create The File
Systemd services exist at
. If you look on your system, they're all there. Actually, open up
. Scan through, and see what's there. You probably won't know everything, but you can certainly understand some of it and recognize just how simple it is. Any
file that you create in that directory can be run as a service, if you construct it properly. Create a file that you would like with the
The first section that you need to write is the
. For a basic service, all that you need is a basic description of your service. Start it off this way.
Description=A bit about your service
block is the bulk of the content of the configuration. This is the block that contains the directives that tell the service how and where to run. Create the block. The first thing that you need to lay out is the type of service that it is. This is just a simple service, so tell systemd that.
This next bit is probably the most important. You need to tell systemd what to execute. This is actually a regular command or a call to a script. Take a look at the example.
ExecStart=/opt/scripts/run-backup.sh --full --to-external
Obviously, you don't have that script, but you can see how you'd just use the same type of command that you'd normally execute. Systemd is also very capable of restarting failed services. This is another parameter that you can set within this configuration. If you want it to restart when it fails, try the following.
It also might be useful to specify a PID file for your service, if it requires one.
If you want or need a specific user or directory to work out of, you can do that too.
You can also set a runtime directory and the file permissions of that directory while in use.
There's plenty more that you can do, but with these basics, you should be able to put together your own simple services and work with existing ones.
Finally, there's the
block. All that you need to do here is specify how your service should be enabled. The most common way to do this is with
That's about all here is for the basics. You can certainly make and modify basic and even slightly more advanced services. Hopefully, you'll gain more confidence working with systemd and become more comfortable creating your own service files with more experience.