Creating a new user with sudo privileges
Linux daemon processes should be run under a user other than root. To create a user with sudo privileges, add the user to the sudo group. The following will show how this can be achieved.
# create a new user on Ubuntu 16.04 adduser new_user # add user to the sudo group usermod -aG sudo new_user # command to remove user and its related home directory # deluser --remove-home new_user # switch to the user su - new_user # navigate to user directory /home/new_user
Setting up systemd process for .Net Core application
To run a .Net Core application under a user, we have to set the .Net Core application file privileges. Before starting the application, remember to update application.json to point to the correct database and directory paths. Assuming that your application is going to run from /home/new_user/dotnetcoreapp
# Granting persmission to directory containing app.dll chmod -R ug+wrx dotnetcoreapp/ # navigate into the directory and test the new privileges # depending on the application, you may need to be in the directory where the app.dll is located cd /home/new_user/dotnetcoreapp sudo dotnet app.dll
If permissions are granted successfully, you should be able to run the application. the next step is to hook it onto a systemd process.
Create Linux daemon process
Create a daemon process to run the application. First, we will need to create the daemon service by creating a new service file under systemd.
# Using a linux file editor like vi or nano (may need to install if you haven't already) sudo nano /etc/systemd/system/kestrel-name_of_the_service.service # Place the following into the new service file # assuming that /home/new_user/dotnetcoreapp is where the application is running from # user_name should have the required permissions [Unit] Description=name_of_the_service on Ubuntu [Service] WorkingDirectory=/home/new_user/dotnetcoreapp ExecStart=/usr/bin/dotnet /home/new_user/dotnetcoreapp/app.dll Restart=always RestartSec=10 SyslogIdentifier=dotnet-name_of_the_service User=new_user [Install] WantedBy=multi-user.target
Start the service using the following commands.
# enable and start the service systemctl enable kestrel-name_of_the_service .service systemctl start kestrel-name_of_the_service .service # you need to restart the service every time you change the service file for it to take effect
Source – Microsoft’s .Net core example