How to create and run worker service C# in Linux?

Running a background process on Linux is a common requirement for developers, especially when deploying worker services built with C#. This guide demonstrates how to configure and manage a systemd service unit to run your C# worker service reliably on Linux.

Step 1: Create a service unit file

Service unit files define the properties and behavior of a background process. Use the .service extension for these files. Here, we’ll create a file named mytool.service:

1
sudo vi /etc/systemd/system/mytool.service

Step 2: Grant execution permission to service

By default, the service does not have execution permissions, so we need to set the appropriate permissions.

1
sudo chmod +x /path/to/my-tool-folder/file-executable

Step 3: Configure service unit file

Add the following configuration to the file mytool.service:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=My Tool Process
After=network.target

[Service]
WorkingDirectory=/path/to/my-tool-folder
ExecStart=/path/to/my-tool-folder/file-executable
Type=simple
Restart=always
# Restart service after 30 seconds if the service crashes:
RestartSec=30
Environment=DOTNET_ENVIRONMENT=Production

[Install]
WantedBy=default.target

Save and exit the editor.

Step 4: Reload and start service

Reload systemd to apply the changes:

1
sudo systemctl daemon-reload

Step 5: Start the service

1
sudo systemctl start mytool.service

You can check its status, stop it using the following commands:

1
2
sudo systemctl status mytool.service
sudo systemctl stop mytool.service

Step 6: Enable service allow it to start on boot

1
sudo systemctl enable mytool.service

Step 7: View and clear Logs

To view logs for your service:

1
sudo journalctl -u mytool.service

To clear the logs:

1
sudo rm -rf /run/log/journal/*

By following these steps, you’ve successfully created a systemd service unit for your application.

 Comments
Comment plugin failed to load
Loading comment plugin