Skip to content

在 Linux 上使用 Systemd 守护 .NET 应用

Systemd 是一个系统和服务管理器,可以自动化和简化 Linux 系统的管理和维护,包括启动、停止和管理后台服务。

相关 .NET 环境安装

进程守护步骤

1. 创建 .service 文件

/etc/systemd/system/ 目录下创建一个名为 myapp.service 的文件,并使用文本编辑器打开并添加以下内容:

ini
[Unit]
Description=My .NET 6 Web API Application
After=network.target

[Service]
WorkingDirectory=/path/to/your/app
ExecStart=/usr/bin/dotnet /path/to/your/app/MyApp.dll
Restart=always
# Use the following line if you want to limit the resources used by the app
# MemoryLimit=1G

[Install]
WantedBy=multi-user.target

注意:将 WorkingDirectoryExecStart 中的路径替换为您的应用程序的实际路径。

2. 启用和启动服务

使用以下命令启用和启动服务:

shell
sudo systemctl enable myapp.service
sudo systemctl start myapp.service

这将启用并启动您的应用程序服务,使其在系统重启后自动启动。

3. 检查服务状态

使用以下命令检查服务状态:

shell
sudo systemctl status myapp.service

如果一切正常,您应该看到服务已经在运行并且没有出现错误。

解释

[Unit] 部分

  • Description:提供服务的简要描述。
  • After:指定服务应在网络目标达成后启动。

[Service] 部分

  • WorkingDirectory:设置服务的工作目录为应用程序的位置。
  • ExecStart:指定要运行以启动应用程序的命令。
  • Restart:将服务设置为在失败或停止时自动重新启动。
  • MemoryLimit(可选):限制服务可以使用的内存量。

[Install] 部分

  • WantedBy:指定此服务应该与哪个目标一起启动。

要使用此 unit 文件,您需要将其保存为 .service 扩展名,并将其放置在 /etc/systemd/system 目录下。然后运行 systemctl daemon-reload 命令使 systemd 意识到新服务。然后可以使用 systemctl start <service_name> 命令启动服务,其中 <service_name> 是不带 .service 扩展名的 unit 文件的名称。

常用命令

以下是一些常用的 Systemd 命令,用于管理 .NET 应用程序服务:

  • 重载 Systemd 配置

    shell
    sudo systemctl daemon-reload
  • 启动服务

    shell
    sudo systemctl start myapp.service
  • 停止服务

    shell
    sudo systemctl stop myapp.service
  • 禁用服务(停止服务并在系统启动时不再自动启动):

    shell
    sudo systemctl disable myapp.service
  • 重启服务

    shell
    sudo systemctl restart myapp.service
  • 查看服务状态

    shell
    sudo systemctl status myapp.service

参考资料

Netshare