Ubuntu – How to make the systemd service run via specific user and start on boot

systemd

I just upgraded from Ubuntu server 14 to version 15. I had trouble getting my upstart script working after the upgrade, and read that systemd is the new default. I'm far from a linux expert, so please go easy on me 🙂

Here is what my upstart script was before:

description "NZBGet upstart script"

setuid robert
setgid robert

start on runlevel [2345]
stop on runlevel [016]

respawn

expect fork

script
    exec nzbget -D
end script

pre-stop script
    exec nzbget -Q
end script

Based on the upstart to systemd wiki page, I used the tables provided there to map things as closely as I could in my new systemd service file:

[Unit]
Description=NZBGet Service

[Service]
Type=forking
ExecStart=/usr/local/bin/nzbget -D
ExecStop=/usr/local/bin/nzbget -Q
Restart=on-failure

This file is located at /home/robert/.config/systemd/user/nzbget.service. To start the service manually, I've been doing:

$ systemctl --user start nzbget

This works great. However, when I log out of my SSH session, the service shuts down. Also, it does not start on bootup or user login. I want it to behave the same as it did as an upstart service: I want it to start at boot, run constantly, and as a specific user.

What do I need to do to get this configuration?

Best Answer

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 which 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/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.

Related Question