本篇主要介绍如何在CentOS7上把.net core控制台app部署为一个后台长期运行的服务。
1. 在CentOS7上安装dotnet 2.0 SDK
参考官网操作步骤:https://docs.microsoft.com/en-us/dotnet/core/linux-prerequisites?tabs=netcore2x
安装完查看.net core版本。执行dotnet --info 或者dotnet --version命令。
2. 新建.net core控制台项目
● dotnet new console -o hellonetcore
● 进入hellonetcore目录,编辑Program.cs
● 运行hellonetcore项目
● 发布hellonetcore项目
发布完后在Release目录生成发布publish目录。
3. 部署服务
● 创建服务脚本并放在/lib/systemd/system 目录下
运行
dotnet hellonetcore.dll
后台运行
作为后台进程运行:
nohup dotnet hellonetcore.dll &
ps -ef 查看所有进程
kill 8738 进程号 关闭进程
● 使用systemctrl命令部署服务
systemctrl daemon-reload
systemctrl start hellonetcore
systemctrl status hellonetcore
到此一个完整的CentOS 系统服务部署完成。使用systemctrl is-active 命令查看服务是否运行状态:
4. 注意事项
● 对于console程序,需要客户端自己保障主程序不退出,本实例中采用while(true)方式,也可以仿照asp.net core中的ManualResetEventSlim方式。如果没有阻塞主程序退出,当执行systemctrl start hellonetcore命令时会是如下结果: