How do I make my systemd service run via specific user and start on boot?

Solution 1:

First problem

You can specify the directives User= and Group= in the [Service] section of the unit file.

Second problem

To make the service run on boot, you should not put it in your home folder. Instead, put it under /etc/systemd/system/. This is the folder meant to be used by the system administrator (i.e. you) to add new system-wide services.

Other folders include:

  • /usr/lib/systemd/system/ is meant for packages that want to install unit files, though under Debian and Ubuntu the folder is actually /lib/systemd/system/ because the various bin and lib folders have not been merged into a unified /usr/ prefix yet.
  • /usr/local/lib/systemd/system/ is for installing units by locally compiled packages.

Testing the unit

Once the unit file is in an appropriate location, you can try starting the unit immediately by typing systemctl start <UNIT_FILENAME> as usual. It should work without having to type the unit's full path. The extension also doesn't have to be specified if it's .service.

Enabling the unit

Before you can enable your unit, you need to add an [Install] section, under which you should add the directive WantedBy=multi-user.target. This directive specifies the stage of the boot-up process during which the service should be started (if it were enabled). multi-user.target is appropriate for most services.

Once that information is added, you can use systemctl enable <UNIT_FILENAME>, which enables the unit, making systemd from now on automatically start it during boot up at the specified stage.

Solution 2:

You might be interested in using systemd's user lingering functionality. It is enabled via loginctl enable-linger USERNAME.

It causes a separate service manager for the respective user being started at boot, so your user-defined units in ~/.config/systemd/user will be picked up and processed at boot and shutdown times according to your service configuration.

You can also use systemctl --user for managing and configuring the service(s), which will operate on your user's service manager, not the one of the system.