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: RequiresMountsFor= makes a systemd service wait until its disk is mounted

Systemd
~/tips/tip-systemd-requiresmountsfor

sudo systemctl edit myapp.service

Keeps a service from starting before the disk or share it writes to is mounted.

A service that keeps its data on a second disk or an NFS share has a nasty failure mode. If it starts before the mount is there, it happily writes into the empty mount point folder on the root disk, and later the real disk is mounted on top of those files. I’d rather the service just waited.

RequiresMountsFor= takes one or more absolute paths. systemd works out which mount units are needed to reach those paths and adds Requires= and After= on them for you, so the service starts only after the mounts are up. A drop-in is enough:

sudo systemctl edit myapp.service

[Unit]
RequiresMountsFor=/mnt/data /mnt/backup

Save, and the next start of myapp.service waits for /mnt/data and /mnt/backup. You don’t need to know the name of the mount unit (mnt-data.mount); the path is enough. You can check the result with systemctl show -p Requires,After myapp.service.

Two caveats. The mount has to exist for systemd, so it needs a line in /etc/fstab or its own .mount unit; a share you mount from a script is invisible here. And Requires= is strict: if the mount fails, the service is not started, and if you stop or unmount it on purpose, the service is stopped too. That is usually what I want for data. When the disk is optional, systemd 256 added WantsMountsFor=, which orders the same way with the softer Wants=.

Further reading: systemd.unit(5) manual 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