要在Linux上创建一个.NET Core应用作为服务运行,你可以使用systemd来管理你的服务。以下是创建服务的基本步骤和示例代码:
-
确保你的.NET Core应用已经发布并且可以在Linux上运行。
-
创建一个新的systemd服务文件。
创建一个名为yourapp.service的文件,替换yourapp为你的应用名。
[Unit]
Description=Your .NET App as a service
[Service]
WorkingDirectory=/var/www/yourapp
ExecStart=/var/www/yourapp/YourApp
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-yourapp
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target
替换WorkingDirectory和ExecStart为你的应用的实际路径和执行文件。
-
将服务文件复制到
/etc/systemd/system/目录。
sudo cp yourapp.service /etc/systemd/system/
-
重新加载systemd配置。
sudo systemctl daemon-reload
-
启动你的服务并设置为开机启动。
sudo systemctl start yourapp.service
sudo systemctl enable yourapp.service
确保你的.NET Core应用有执行权限:
sudo chmod +x /var/www/yourapp/YourApp
你可以使用以下命令检查服务状态:
sudo systemctl status yourapp.service
如果你需要调试服务,你可以查看日志:
journalctl -u yourapp.service
以上步骤和代码是创建一个基本的.NET Core服务的方法,你可能需要根据你的应用和环境做出调整。