Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Writing a Linux daemon in C#

June 7, 2017
Takayoshi Tanaka
Related topics:
.NET
Related products:
Red Hat Enterprise Linux

Share:

    When you want to run .NET Core process as a daemon on Red Hat Enterprise Linux, you can create a custom systemd unit. Today I'll write about two examples of custom systemd unit for .NET Core. The one is a oneshot type for running a .NET Core console application and the other is a simple type for running an ASP.NET Core Web application.

    Oneshot type with a console application

    Building an app

    You can use dotnet run in systemd with specifying project directory as a working directory. However, let's build a binary file and use it for systemd. Create your project with dotnet new end edit Program.cs as followed.

    using System;
    using System.IO;
    
    namespace ConsoleApplication
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var path = Path.GetTempFileName();
                File.WriteAllText(path, "Hello Temp File!");
                Console.WriteLine($"Wrote temp file: {path}");
            }
        }
    }

    Then publish the project with dotnet publish command. You will see the binary files under bin/<Configuration>/<Framework> directory.

    $ dotnet publish -c Release
    Publishing ConsoleApp for .NETCoreApp,Version=v1.1
    Project ConsoleApp (.NETCoreApp,Version=v1.1) was previously compiled. Skipping compilation.
    publish: Published to /home/tatanaka/Documents/git/tanaka-takayoshi/SystemdExample/1.1/ConsoleApp/bin/Release/netcoreapp1.1/publish
    Published 1/1 projects successfully

    Creating a custom systemd

    At first, create a user for running daemon and a working directory.

    $ sudo useradd -s /sbin/nologin dotnetuser
    $ sudo mkdir /var/SystemdExample
    $ sudo cp /home/tatanaka/Documents/git/tanaka-takayoshi/SystemdExample/1.1/ConsoleApp/bin/Release/netcoreapp1.1/publish/* /var/SystemdExample
    $ sudo chown -R dotnetuser:dotnetuser /var/SystemdExample

    Then create a custom systemd unit file under /etc/systemd/system/ directory. File name should be <unit-name>.<unit-type>. I created /etc/systemd/system/netcore-console-example.service.

    [Unit]
    Description=Example for .NET Core ConsoleApp with systemd
    DefaultDependencies=no
    
    [Service]
    Type=oneshot
    RemainAfterExit=no
    ExecStart=/opt/rh/rh-dotnetcore11/root/usr/bin/dotnet ConsoleApp.dll
    WorkingDirectory=/var/SystemdExample
    User=dotnetuser
    Group=dotnetuser
    
    
    [install]

    You should specify the full path of dotnet in ExecStart. The above is the case of Red Hat provided .NET Core 1.1. Then you can execute the daemon with systemctl command. You can see the console output with systemctl status command or journalctl command.

    $ sudo systemctl start netcore-console-example.service 
    $ sudo systemctl status netcore-console-example.service 
    ● netcore-console-example.service - Example for .NET Core ConsoleApp with systemd
       Loaded: loaded (/etc/systemd/system/netcore-console-example.service; enabled; vendor preset: disabled)
       Active: inactive (dead) since Fri 2017-02-24 00:29:16 JST; 13s ago
      Process: 18075 ExecStart=/opt/rh/rh-dotnetcore11/root/usr/bin/dotnet ConsoleApp.dll (code=exited, status=0/SUCCESS)
     Main PID: 18075 (code=exited, status=0/SUCCESS)
    
    Feb 24 00:29:16 localhost.localdomain systemd[1]: Starting Example for .NET Core ConsoleApp with systemd...
    Feb 24 00:29:16 localhost.localdomain dotnet[18075]: Wrote temp file: /tmp/tmph1ok6H.tmp
    Feb 24 00:29:16 localhost.localdomain systemd[1]: Started Example for .NET Core ConsoleApp with systemd.
    
    $ journalctl -u netcore-console-example.service -e
    Feb 24 00:29:16 localhost.localdomain systemd[1]: Starting Example for .NET Core ConsoleApp with systemd...
    Feb 24 00:29:16 localhost.localdomain dotnet[18075]: Wrote temp file: /tmp/tmph1ok6H.tmp
    Feb 24 00:29:16 localhost.localdomain systemd[1]: Started Example for .NET Core ConsoleApp with systemd.
    $ sudo cat /tmp/tmph1ok6H.tmp
    Hello Temp File!

    Working with PrivateTemp

    In the above systemd unit, the program writes a file under temp folder. You sometimes want to write a temp file, which is secured from other users. You can use PrivateTemp with specifying in [Service] section.

    [Service]
    Type=oneshot
    RemainAfterExit=no
    ExecStart=/opt/rh/rh-dotnetcore11/root/usr/bin/dotnet ConsoleApp.dll
    WorkingDirectory=/var/SystemdExample
    User=dotnetuser
    Group=dotnetuser
    PrivateTemp=true

    After reloading the unit file, the program can access /tmp directory as before, but this is not an actual /tmp directory.

    $ sudo systemctl daemon-reload 
    $ sudo systemctl start netcore-console-example.service
    $ sudo systemctl status netcore-console-example.service
    ● netcore-console-example.service - Example for .NET Core ConsoleApp with systemd
       Loaded: loaded (/etc/systemd/system/netcore-console-example.service; enabled; vendor preset: disabled)
       Active: inactive (dead) since Fri 2017-02-24 00:35:46 JST; 12s ago
      Process: 18415 ExecStart=/opt/rh/rh-dotnetcore11/root/usr/bin/dotnet ConsoleApp.dll (code=exited, status=0/SUCCESS)
     Main PID: 18415 (code=exited, status=0/SUCCESS)
    
    Feb 24 00:35:46 localhost.localdomain systemd[1]: Starting Example for .NET Core ConsoleApp with systemd...
    Feb 24 00:35:46 localhost.localdomain dotnet[18415]: Wrote temp file: /tmp/tmpJLWAGC.tmp
    Feb 24 00:35:46 localhost.localdomain systemd[1]: Started Example for .NET Core ConsoleApp with systemd.
    $ ls /tmp/tmpJLWAGC.tmp
    ls: cannot access /tmp/tmpJLWAGC.tmp: No such file or directory

    Simple type with a web application

    Building an app

    Now let's build an ASP.NET Core web application. Today I use a default template project.

    $ dotnet new -t web
    Created new C# project in /home/tatanaka/Documents/git/tanaka-takayoshi/SystemdExample/1.1/WebApp.
    $ dotnet restore 
    ** snipped**
    log  : Restore completed in 9721ms.
    $ dotnet publish -c Release
    Publishing WebApp for .NETCoreApp,Version=v1.1
    ** snipped **
    publish: Published to /home/tatanaka/Documents/git/tanaka-takayoshi/SystemdExample/1.1/WebApp/bin/Release/netcoreapp1.1/publish
    Published 1/1 projects successfully

    Now it can be run with dotnet command.

    $ dotnet bin/Release/netcoreapp1.1/publish/WebApp.dll 
    info: Microsoft.Extensions.DependencyInjection.DataProtectionServices[0]
          User profile is available. Using '/home/tatanaka/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
    Hosting environment: Production
    Content root path: /home/tatanaka/Documents/git/tanaka-takayoshi/SystemdExample/1.1/WebApp
    Now listening on: http://localhost:5000
    Application started. Press Ctrl+C to shut down.

    Creating a custom systemd

    I use the same dotnetuser for this Web Application.

    $ sudo mkdir /var/SystemdExample
    $ sudo cp -R bin/Release/netcoreapp1.1/publish/* /var/SystemdWebExample
    $ sudo chown -R dotnetuser:dotnetuser /var/SystemdWebExample

    Then create a custom systemd unit file /etc/systemd/system/netcore-web-example.service.

    [Unit]
    Description=Example for .NET Core WebApp with systemd
    DefaultDependencies=no
    Wants=network.target # network is required
    After=network.target
    
    [Service]
    ExecStart=/opt/rh/rh-dotnetcore11/root/usr/bin/dotnet WebApp.dll
    WorkingDirectory=/var/SystemdWebExample
    Restart=always
    RestartSec=10   # Restart service after 10 seconds if dotnet service crashes
    SyslogIdentifier=dotnet-example
    User=dotnetuser
    Group=dotnetuser
    PrivateTmp=true
    Environment=ASPNETCORE_ENVIRONMENT=Production # specify environment variable for environment
    Environment=ASPNETCORE_URLS=http://*:8080 # specify environement variable for listening port
    
    [Install]
    WantedBy = multi-user.target

    Finally, you can run ASP.NET Core application as a Linux daemon. Please note this application listens to port 8080 instead of ASP.NET Core default 5000 as I specify environment variable in ASPNETCORE_URLS the unit file.

    $ systemctl start netcore-web-example.service
    [tatanaka@localhost WebApp]$ systemc^C
    [tatanaka@localhost WebApp]$ sudo systemctl status netcore-web-example.service
    [sudo] password for tatanaka: 
    ● netcore-web-example.service - Example for .NET Core WebApp with systemd
       Loaded: loaded (/etc/systemd/system/netcore-web-example.service; disabled; vendor preset: disabled)
       Active: active (running) since Sat 2017-02-25 01:02:12 JST; 11s ago
     Main PID: 7041 (dotnet)
       CGroup: /system.slice/netcore-web-example.service
               └─7041 /opt/rh/rh-dotnetcore11/root/usr/bin/dotnet WebApp.dll
    
    Feb 25 01:02:12 localhost.localdomain systemd[1]: Started Example for .NET Core WebApp with systemd.
    Feb 25 01:02:12 localhost.localdomain systemd[1]: Starting Example for .NET Core WebApp with systemd...
    Feb 25 01:02:12 localhost.localdomain dotnet-example[7041]: info: Microsoft.Extensions.DependencyInjection.DataProtectionServices[0]
    Feb 25 01:02:12 localhost.localdomain dotnet-example[7041]: User profile is available. Using '/home/dotnetuser/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
    Feb 25 01:02:13 localhost.localdomain dotnet-example[7041]: Hosting environment: Production
    Feb 25 01:02:13 localhost.localdomain dotnet-example[7041]: Content root path: /var/SystemdWebExample
    Feb 25 01:02:13 localhost.localdomain dotnet-example[7041]: Now listening on: http://*:8080
    Feb 25 01:02:13 localhost.localdomain dotnet-example[7041]: Application started. Press Ctrl+C to shut down.
    
    $ journalctl -u netcore-web-example -xf
    -- Logs begin at Mon 2017-02-20 11:58:31 JST. --
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: Sending file. Request path: '/images/banner4.svg'. Physical path: '/var/SystemdWebExample/wwwroot/images/banner4.svg'
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: Request finished in 0.1973ms 200 image/svg+xml
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: Request starting HTTP/1.1 GET http://localhost:8080/favicon.ico
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: Sending file. Request path: '/favicon.ico'. Physical path: '/var/SystemdWebExample/wwwroot/favicon.ico'
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
    Feb 25 01:02:36 localhost.localdomain dotnet-example[7041]: Request finished in 0.5824ms 200 image/x-icon

    However, this is not enough for production usage for ASP.NET Core. You may have to set up a reverse proxy server like nginx, firewalls and so on. Also, if you would like to know much more about systemd, please refer our document.

    For additional information and articles on .NET Core visit our .NET Core web page for more on this topic.

     


    Whether you are new to Linux or have experience, downloading this cheat sheet can assist you when encountering tasks you haven’t done lately.

    Last updated: February 22, 2024

    Recent Posts

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    • How to integrate vLLM inference into your macOS and iOS apps

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue