Configure Systemd Service to Continue to Run when the user session ends (CentOS/RHEL 8)

Question: When a user logs out of their session any service they’ve started using the systemd user process is terminated. How this can be avoided?

The systemd login manager will terminate any user services when their login session ends unless you enable user lingering with the enable-linger option. Use loginctl with the enable-linger option to configure a user to start during the boot process and prevent the systemd service from terminating when the user session ends.

Here is an example with a user called user:

# loginctl enable-linger user

This option will still require the user to log in and start the service but will prevent it from terminating when the user logs out.

Here is an example of what this would look like with a user called user with an ID of 1000 after the change was made and the system was rebooted:

1. Run the systemd-cgls command and look for the user. In this example look for user-1000.

# systemd-cgls
│ └─user-1000.slice
│   └─[email protected]
│     └─init.scope
│       ├─894 /usr/lib/systemd/systemd --user
│       └─912 (sd-pam)

The user exists but there is currently no bash session.

2. Log in as the user from another terminal and then re-run the systemd-cgls command from the root terminal.

# systemd-cgls
│ └─user-1000.slice
│   ├─[email protected]
│   │ └─init.scope
│   │   ├─894 /usr/lib/systemd/systemd --user
│   │   └─912 (sd-pam)
│   └─session-4.scope
│     ├─1415 sshd: user [priv]
│     ├─1418 sshd: user@pts/1
│     └─1419 -bash

You should now see the bash session.

3. Start the service from the other terminal as the user and then log out. In this example the systemd service is called test.service.

$ systemctl --user start test.service
$ logout

4. Run the systemd-cgls command to verify the systemd –user process and the service is still running after the user has logged out.

# systemd-cgls
│ └─user-1000.slice
│   └─[email protected]
│     ├─test.service
│     │ └─1448 /usr/bin/sleep 1000
│     └─init.scope
│       ├─894 /usr/lib/systemd/systemd --user
│       └─912 (sd-pam)