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: RemainAfterExit=yes keeps a one-shot systemd service marked as active

Systemd
~/tips/tip-systemd-oneshot-remainafterexit

RemainAfterExit=yes

Keeps a run-once setup service active after its script exits, so stop runs cleanly.

Some jobs at boot aren’t daemons at all. They set something up and exit, like a handful of firewall rules or a network tweak. Type=oneshot is made for that, but on its own it has a quirk I find a bit odd.

A plain oneshot service goes back to “inactive” as soon as its command finishes. So every systemctl start, or any unit that pulls it in, runs the script again, and an ExecStop= never gets used because the unit was never active. RemainAfterExit=yes fixes that: after a successful run, systemd keeps the unit marked as active until you stop it.

[Unit]
Description=Set up my extra rules

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/myrules-up
ExecStop=/usr/local/sbin/myrules-down

[Install]
WantedBy=multi-user.target

This is close to the “simple firewall” example in the systemd.service manual. At boot myrules-up runs once, and because it is a oneshot, units ordered after it wait until it has finished. systemctl status shows it as active even though no process is left, and systemctl stop (or a shutdown) runs myrules-down. I like how that gives a setup script a clean on and off switch.

The catch: because the unit now counts as active, systemctl start does nothing the second time. If you changed the script and want to run it again, use systemctl restart, which runs the stop command and then the start command. Also note that a oneshot service can’t use Restart=always or Restart=on-success; systemd refuses those for this type.

Further reading: systemd.service(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