Dotnet systemd service file as user

Date: 2022-04-26
# create or copy the service file in /etc/systemd/user
vim /etc/systemd/user/$servicename.service

# create service user (only when you have not one already)
useradd -m -U $username

# log in as the user
su - $username -s /bin/bash
systemctl --user daemon-reload

# test run in the current console (foreground)
systemctl --user console $servicename

# you're able to user the commands below WITHOUT sudo/root!
systemctl --user start $servicename
systemctl --user stop $servicename
systemctl --user status $servicename
# run at user-login
systemctl --user enable $servicename

# run as root: start user at boot/leave at logout
loginctl enable-linger $username
[Unit]                                                             
Description=$servicename
[Service]                                                          
ExecStart=/usr/bin/dotnet /home/$username/$servicename/Build/WebApi.dll
Restart=always                                                     
RestartSec=10                                                      
KillSignal=SIGINT                                                  
SyslogIdentifier=$servicename                                 
#User=(NOT AVAILABLE IN USER MODE)
#Group=(NOT AVAILABLE IN USER MODE)                                               
Environment=ASPNETCORE_ENVIRONMENT=production                      
Environment=DOTNET_CLI_TELEMETRY_OPTOUT=1                          
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false                   
WorkingDirectory=/home/$username/$servicename/Build/                   
                                                                   
[Install]                                                          
WantedBy=default.target    
#WantedBy=multi-user.target (NOT AVAILABLE IN USER MODE)

Example update script: (WITHOUT sudo/root)

#!/bin/bash
systemctl --user stop $servicename
git pull
dotnet publish -c Release WebApi/WebApi.csproj -o Build/
systemctl --user start $servicename
61390cookie-checkDotnet systemd service file as user