如何从.NET Core控制台应用程序创建Linux守护程序? [英] How do you create a Linux daemon from a .NET Core console application?
问题描述
我习惯于使用Topshelf创建Windows服务.借助.NET Core和跨平台的前景,这引发了许多有趣的场景:
I'm used to creating Windows services using Topshelf. With .NET Core and the prospect of going cross-platform, this raises a number of interesting scenarios:
- 鉴于Topshelf尚不支持.NET Core,如何为.NET Core创建Windows服务? (一种方法可能是创建一个常规的.NET Core控制台应用程序并将其与NSSM一起安装,但这不提供启动/停止的挂钩,因此无法正常停止该服务.)
- 您如何在Linux上做同样的事情?没有Windows服务,但是有守护进程的概念. 此答案提供了一种基本方法,但是需要额外的工作并且依赖于某些基础软件.
- 上面的#1和#2是否可以使用跨平台方法来完成,还是有必要针对每个平台来解决此问题(例如使用预处理器指令)?
- Given that Topshelf does not yet support .NET Core, how can I create Windows services for .NET Core? (One approach could be to create a regular .NET Core console application and install it with NSSM, but that doesn't provide hooks for Start/Stop, so there is no way to gracefully stop the service).
- How do you do the same thing on Linux? There are no Windows services, but there is the concept of daemon processes. This answer provides a basic approach, but requires additional work and depends on certain underlying software.
- Can #1 and #2 above be done using a cross-platform approach, or is it necessary to tackle this per platform (e.g. with preprocessor directives)?
以上主要是上下文.出于这个问题的目的,我想知道我需要采取哪些步骤,才能使用.NET Core在Linux上运行等效于Windows服务的功能.如果可以在各个平台上以统一的方式做到这一点,那就更好了.
The above is mainly just context. For the purpose of this question, I'd like to know what steps I need to take in order to run the equivalent of a Windows service on Linux, using .NET Core. If this can be done in a unified way across the platforms, even better.
推荐答案
我认为没有针对此的跨平台解决方案.服务是针对特定平台的,即AFAIK.
I dont think there is a cross platform solution for this. Sevices are pretty platform specific, AFAIK.
对于#2,如果要在systemd
下运行.NET Core,则应该能够执行此操作而无需更改任何代码.您基本上需要做的就是发布您的应用程序,然后创建一个systemd
unit
文件来描述您的守护程序. systemd
然后将处理启动,重新启动和终止您的应用程序.
For # 2, you should be able to do this without any code changes if you want run .NET Core under systemd
. All you basically need to do is publish your application, and then create a systemd
unit
file to describe your daemon. systemd
will then handle starting, restarting and killing your applications.
这里有一个systemd单位文件的示例,可作为服务运行ASP.NET Core应用程序:
There is an example of a systemd unit file here to run a ASP.NET Core application as a service: https://docs.microsoft.com/en-us/aspnet/core/publishing/apache-proxy#monitoring-our-application
[Unit]
Description=Example .NET Application
[Service]
WorkingDirectory=/var/aspnetcore/hellomvc
ExecStart=/usr/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll
Restart=always
RestartSec=10
SyslogIdentifier=dotnet-example
User=apache
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target
这篇关于如何从.NET Core控制台应用程序创建Linux守护程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!