How to Rename a Systemd Service Without Stopping or Restarting

systemd

There are multiple reasons to have to rename a systemd service in production. For example:

  • to better differentiate it from a new one
  • because your boss ordered it
  • because of legacy scripts

Assuming a new generic service created in /etc/systemd/system/foo.service and enabled and started as follow: [1]

systemctl daemon-reload
systemctl enable --now foo

Then, you may want to rename it from foo.service to bar.service without impacting the related process in any way.

In normal circumstances you can just do something like this:

mv foo.service bar.service
systemctl daemon-reload
systemctl disable foo
systemctl enable  bar

Then you obtain:

  • systemctl status foo: running not-found disabled
  • systemctl status bar: not-running enabled

So you may want to fix with:

systemctl stop  foo
systemctl start bar

Or with a reboot. However in production environments this is not feasible since you don't want to stop the application for such change. Additionally, reboots are scheduled after months or years. At the same time, it's risky to keep for a long time a stopped service like bar that should not be started by mistake before stopping the not-found running foo.

In short. What approach would you use to rename a systemd service in production?

The ideal condition would be to have the two services backward compatible. Thus, stopping foo also stops bar and vice versa.


Best Answer

There may be some better method that I am unaware of, but this comes to mind as a workaround that mostly gets you what you need until you have the chance to restart the service:

  1. Create a symlink with the desired new name which points to the existing service file (and systemctl daemon-reload).
    Systemd treats symlinks to units as aliases instead of separate units, meaning that both names will now refer to the same unit (same status, same everything).
  2. Plan to actually replace the service during your next maintenance window.