Systemd user instance is killed when user logout

27 Aug 2020

Recently I met a system issue on ubuntu server. I have a user level systemd service run on the server. Each time I ssh login to check it, it’s working. But it didn’t do its jobs.

After I add a restart notification to that server. I found that, each time I login, the server will start, and will stop after I logout.

At that point, I still not realize it’s related to the user session. Because the system service is already working for about 1 year. I just met this issue recently. So I start to think what I have done recently. The one thing I did different with before is I didn’t use tmux recently on server. I just use the default session to do some DevOps works. Then I found it seems related to it.

At last, I found this:

The systemd user instance is started after the first login of a user and killed after the last session of the user is closed.

So this is not a bug, it’s just a behaviour of systemd user instance. The key words to fix this issue is KillUserProcesses mode.

Sometimes it may be useful to start it right after boot, and keep the systemd user instance running after the last session closes, for instance to have some user process running without any open session. Lingering is used to that effect.

So we can start to fix it with the lingering feature:

Run bash command:

loginctl enable-linger <username>

Change the logind configuration

/etc/sysrtemd/logind.conf
[Login]
...
KillUserProcesses=no
...

Run bash command:

systemctl restart systemd-logind

Above configurations will prevent the user process be killed after you logout. Now everyting is ok.

References

Back to top