brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: StateDirectory= gives a systemd service its own folder under /var/lib

Systemd
~/tips/tip-systemd-state-directory

[Service]

Let systemd create and own the data folder of a service, with the right user.

Most services need one folder to write data to. Creating it by hand, with the right owner, on every new box is an easy step to forget.

One line takes care of it:

[Service]
User=myapp
StateDirectory=myapp
ExecStart=/usr/local/bin/myapp --data "$STATE_DIRECTORY"

Before starting the service, systemd creates /var/lib/myapp and gives it to the user from User=. The path is also handed to the process in $STATE_DIRECTORY. With User=svc1, the folder ends up owned by svc1:svc1 and a service that echoes the variable prints dir=/var/lib/myapp.

There are siblings for other kinds of data: CacheDirectory= under /var/cache, LogsDirectory= under /var/log, RuntimeDirectory= under /run and ConfigurationDirectory= under /etc. The runtime one is removed when the service stops; the others stay.

I think it plays very well with hardening. With ProtectSystem=strict the whole file system is read-only for the service, but these directories stay writable, so you do not need an extra ReadWritePaths=.

Be careful with an existing folder: systemd changes the owner of a pre-existing state directory to the service user. Do not point it at a path that other programs also use.

Further reading: systemd.exec man page

More Systemd tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass – dbpass.cred systemd-analyze timespan 1h30min All Systemd tips (88) All topics

Link