本篇主要介紹如何在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 目錄下

● 使用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命令時會是如下結果:

5. 參考鏈接
● systemd教程 :http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html
● systemctrl教程:https://www.freedesktop.org/software/systemd/man/systemd.unit.html,
● dotnet 命令行教程: https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet?tabs=netcore2x
● aspnet core在Linux部署教程: https://docs.microsoft.com/en-us/aspnet/core/publishing/linuxproduction?tabs=aspnetcore2x