Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

为.net Core 3.0 WebApi 创建Linux守护进程 #10

Open
ren8179 opened this issue Mar 15, 2020 · 0 comments
Open

为.net Core 3.0 WebApi 创建Linux守护进程 #10

ren8179 opened this issue Mar 15, 2020 · 0 comments

Comments

@ren8179
Copy link
Owner

ren8179 commented Mar 15, 2020

前言

我们一般可以在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

参考资料

微软官方文档

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant