- 創建服務文件: 打開一個新的.service文件在/etc/systemd/system/目錄下,例如myapp.service
sudo nano /etc/systemd/system/myapp.service
- 編輯服務文件: 添加以下內容到myapp.service文件,確保修改ExecStart以指向你的.NET Core應用程序的可執行文件,以及其他的路徑和配置根據你的需求:
[Unit]
Description=My .NET Core Application[Service]
WorkingDirectory=/path/to/your/app
ExecStart=/usr/bin/dotnet /path/to/your/app/YourApp.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-app
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production[Install]
WantedBy=multi-user.target
- WorkingDirectory: 應用程序的工作目錄。
- ExecStart: 啟動應用程序的命令。
- Restart: 服務失敗時的重啟策略,always表示總是重啟。
- RestartSec: 重啟前等待的時間。
- KillSignal: 系統用于停止服務的信號。
- User: 運行此服務的用戶。
- Environment: 設置環境變量,如ASP.NET Core環境。
注:如何知道ExecStart中命令的路徑呢?
答:which命令會在您的系統的PATH環境變量指定的目錄中搜索可執行文件。
which dotnet
我的配置如下:
[Unit]
Description=自動運行程序[Service]
WorkingDirectory=/root/workerservice
ExecStart=/root/dotnet/dotnet /root/workerservice/WorkerServiceForLinux.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-app
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production[Install]
WantedBy=multi-user.target
- 啟用和啟動服務: 重新加載systemd守護進程以讀取新的服務文件,然后啟用并啟動你的服務
sudo systemctl daemon-reload
sudo systemctl enable myapp.service
sudo systemctl start myapp.service
- 檢查服務狀態: 使用以下命令查看服務狀態
sudo systemctl status myapp.service
- 停止與disable 服務
sudo systemctl disable myapp.service
sudo systemctl stop myapp.service
- 通過這些步驟,您的.NET Core應用程序將作為守護進程運行在Debian系統上。如果應用程序崩潰,systemd將按照您在myapp.service文件中定義的Restart和RestartSec選項自動重新啟動它。