前言

我们一般可以在linux服务器上执行 dotnet <app_assembly.dll> 命令来运行我们的.net core webapi应用。但是这样运行起来的应用很不稳定,关闭终端窗口之后,应用也会停止运行。为了让其可以稳定运行,我们需要让它变成系统的守护进程,成为一种服务一直在系统中运行,出现异常时也能重新启动。

linux系统有自己的守护进程管理工具 systemd 。systemd 是内核启动后的第一个用户进程,pid 为1,是所有其它用户进程的父进程。它直接与内核交互,性能出色,可以提供用于启动、停止和管理进程的许多强大的功能。我们完全可以将程序交给 systemd ,让系统统一管理,成为真正意义上的系统服务。

systemctl 用于管理 systemd 的行为,替换之前的 sysvinit 和 upstart。

创建服务文件

创建服务定义文件:

vim /etc/systemd/system/qf-intecabinet.service

以下是应用的一个示例服务文件:

[unit]
description=运行qf.intecabinet服务

[service]
workingdirectory=/opt/intecabinet # 依赖环境,可以指定多个
execstart=/usr/bin/dotnet /opt/intecabinet/qf.intecabinet.webapi.dll
restart=always
# restart service after 10 seconds if the dotnet service crashes:
restartsec=10
killsignal=sigint
syslogidentifier=qf-intecabinet
user=root # 管理服务的用户,用户必须存在并且拥有正确应用文件的所有权
environment=aspnetcore_environment=production # 环境变量
environment=dotnet_print_telemetry_message=false

[install]
wantedby=multi-user.target # 该服务所在的target

管理服务

保存该文件并启用该服务

systemctl enable qf-intecabinet.service

启动该服务

systemctl start qf-intecabinet.service

查看服务状态

systemctl status qf-intecabinet.service

查看日志

journalctl -fu qf-intecabinet.service

使用时间选项(如 –since today、–until 1 hour ago)或这些选项的组合可以减少返回的条目数

journalctl -fu qf-intecabinet.service --since "2020-01-01" --until "2020-03-01 12:00"

关闭服务

systemctl stop qf-intecabinet.service

参考资料

到此这篇关于.net core 3.0 webapi 创建linux守护进程的方法的文章就介绍到这了,更多相关.net core webapi创建守护进程内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!