systemd-tmpfiles Explained: Creating and Cleaning Files Declaratively

systemd-tmpfiles Explained: Creating and Cleaning Files Declaratively

Something creates /run/myservice before your daemon starts. Something deletes files in /tmp after ten days. Something wrote a value into /sys at boot. All three are systemd-tmpfiles, and its configuration is one of the more useful systemd mechanisms that nobody reads about.

Where the configuration lives

Three directories, in increasing priority:

ls /usr/lib/tmpfiles.d/     # vendor, do not edit
ls /run/tmpfiles.d/         # runtime generated
ls /etc/tmpfiles.d/         # yours

A file in /etc with the same name as one in /usr/lib replaces it entirely. It does not merge. That is the mechanism for overriding a vendor rule, and it means you must reproduce the lines you still want.

# what is actually in effect
systemd-analyze cat-config tmpfiles.d | head -40

# what would happen, without doing it
sudo systemd-tmpfiles --create --dry-run
sudo systemd-tmpfiles --clean --dry-run

--dry-run before anything. This tool deletes files, and a rule with a wrong path is a rule that deletes the wrong files.

The format

#Type Path                Mode User Group Age Argument
d     /run/myapp          0755 myapp myapp -   -
f     /var/log/myapp.log  0640 myapp adm   -   -
L     /etc/myapp/current  -    -    -     -   /etc/myapp/v2
w     /sys/class/backlight/intel_backlight/brightness - - - - 800

Seven whitespace-separated fields. A dash means “unspecified” and is not the same as empty.

The types worth knowing:

TypeDoes
fCreate a file if absent
f+Create or truncate
wWrite to an existing file
w+Append to an existing file
dCreate a directory, leave contents
DCreate a directory, empty it on boot
eAdjust an existing directory, apply ageing
LCreate a symlink
L+Create a symlink, replacing what is there
CCopy, if the target does not exist
rRemove a file or empty directory
RRemove recursively
zAdjust mode, owner and SELinux label
ZAs z, recursively
xExclude from cleaning
XExclude the path itself from cleaning

d versus D is the distinction to get right. Lowercase leaves contents alone. Uppercase empties the directory whenever tmpfiles runs in remove mode, which includes every boot.

r and R delete things. Read them twice.

A ! prefix means boot-only, and a - prefix means ignore errors:

# only at boot, not on a daily run
!d /run/something 0755 root root -
# do not fail if the path is missing
-r /tmp/maybe-absent

The ageing field, which explains /tmp

# from /usr/lib/tmpfiles.d/tmp.conf, roughly
q /tmp 1777 root root 10d
q /var/tmp 1777 root root 30d

That is why files in /tmp disappear after ten days. The age field tells systemd-tmpfiles --clean how old something must be before removal, and a timer runs it daily.

systemctl status systemd-tmpfiles-clean.timer
systemctl list-timers systemd-tmpfiles-clean.timer

Age is measured against atime, ctime and mtime, taking the most recent, so a file being read keeps it alive. You can be specific:

d /var/cache/myapp 0755 myapp myapp 7d
# or by mtime only
d /var/cache/myapp 0755 myapp myapp 7d - mtime

On many systems /tmp is also a tmpfs, so a reboot clears it regardless of ageing:

findmnt /tmp
systemctl status tmp.mount

Two separate mechanisms, same practical result: do not leave anything you want in /tmp. Our /tmp guide covers both, and /var/tmp is the one that survives reboots.

Stopping it cleaning something

# /etc/tmpfiles.d/keep-my-stuff.conf
x /tmp/keep-this-forever
X /tmp/keep-the-dir-itself

Or set the age to a dash in an overriding file, which disables ageing for the path.

Where you actually want it

Runtime directories before a service starts

# /etc/tmpfiles.d/myapp.conf
d /run/myapp 0755 myapp myapp -
d /run/myapp/sockets 0750 myapp www-data -

Useful when a path must exist before anything starts, or is shared between services.

For a single service, the unit file is better:

[Service]
User=myapp
RuntimeDirectory=myapp
RuntimeDirectoryMode=0755
StateDirectory=myapp
CacheDirectory=myapp
LogsDirectory=myapp

RuntimeDirectory= creates /run/myapp owned by the service user and removes it on stop, which ties the lifetime to the service. That is the right default, and it is one of the directives our service hardening guide covers. Use tmpfiles for the cases it does not fit.

Note that /var/run is a symlink to /run on any modern system, so a file you wrote to /var/run lives on a tmpfs and vanishes at reboot. Our /var guide covers the layout.

Writing to sysfs at boot

# /etc/tmpfiles.d/brightness.conf
w /sys/class/backlight/intel_backlight/brightness - - - - 800
# a kernel tunable that is not a sysctl
w /sys/kernel/mm/transparent_hugepage/enabled - - - - madvise

Tidier than writing a service for a single value. Our sysfs guide covers why nothing in /sys persists.

For device attributes, a udev rule is usually better, because it reapplies when the device appears rather than only at boot. Our udev guide covers the distinction, which matters for anything hot-pluggable.

# the udev equivalent, which survives a device reappearing
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/scheduler}="none"

Fixing permissions declaratively

# ensure ownership and SELinux labels on every boot
Z /var/lib/myapp 0750 myapp myapp -

Z applies recursively and includes the SELinux label, which makes it the right tool after moving a data directory. Our SELinux guide covers why a moved directory stops working, and this is one way to keep it labelled.

Running it

# all three phases
sudo systemd-tmpfiles --create --remove --clean

# one file only, which is how you test your own
sudo systemd-tmpfiles --create /etc/tmpfiles.d/myapp.conf

# with a prefix limit, for safety
sudo systemd-tmpfiles --clean --prefix=/var/cache/myapp

The three phases do different things:

  • --create makes things that should exist
  • --remove removes what r, R and D lines specify
  • --clean ages out files per the age field
systemctl status systemd-tmpfiles-setup.service    # at boot
systemctl status systemd-tmpfiles-clean.timer      # daily

Mistakes worth avoiding

Not using --dry-run. This tool deletes.

Using R on a path with a variable in it, or with a typo. There is no undo, and our testdisk and photorec guide is a poor substitute for not having deleted it.

Expecting /etc to merge with /usr/lib. Same filename means replacement. Check the result:

systemd-analyze cat-config tmpfiles.d | grep -A3 'myapp'

Using tmpfiles where a unit directive fits. RuntimeDirectory=, StateDirectory= and CacheDirectory= are better for service-owned paths because the lifetime is managed.

Forgetting w requires the file to exist. Writing to a sysfs attribute that is not present yet silently does nothing, and that is the usual reason a rule appears to be ignored. Use - prefix if the absence is expected, and a udev rule if the timing is the problem.

Frequently Asked Questions

What does systemd-tmpfiles do?

It creates, adjusts and removes files and directories according to declarative configuration, at boot and on a timer. Services use it to create the runtime directories they need, and the system uses it to age out old files in temporary directories.

Why do files in /tmp disappear?

Because a tmpfiles rule ages them out, typically after ten days, and the timer runs daily. On many systems /tmp is also a tmpfs held in memory, so a reboot clears it entirely. Neither behaviour is a fault and both catch people who left something important there.

What is the difference between the types d and D?

Lowercase d creates a directory if it does not exist and leaves the contents alone. Uppercase D does the same but also empties the directory when systemd-tmpfiles runs in remove mode, which happens at boot. Use D only where the contents are genuinely disposable.

How do I stop systemd-tmpfiles cleaning a directory?

Give the age field a dash in your own configuration file, which disables ageing for that path, and name the file so it overrides the vendor one. A file in /etc with the same name as one in /usr/lib replaces it entirely rather than adding to it.

Can systemd-tmpfiles write to sysfs?

Yes, with the w type, which writes a value into an existing file. It is a tidy way to apply a one-off sysfs setting at boot without writing a service, though a udev rule is usually a better fit for a device attribute because it reapplies when the device appears.

Why does my service need RuntimeDirectory instead of a tmpfiles rule?

RuntimeDirectory in a unit file creates the directory with the service ownership and removes it on stop, which keeps the lifetime tied to the service. A tmpfiles rule is better for paths shared between services or needed before any service starts.