1.创建服务文件: 在 /etc/systemd/system/ 目录下创建一个 .service 文件,例如 myapp.service:
[Unit] Description=My ASP.NET Core Application #服务的名称 After=network.target #服务在网络服务之后启动 [Service] WorkingDirectory=/path/to/your/app ExecStart=/usr/bin/dotnet /path/to/your/app/YourApp.dll --urls http://0.0.0.0:50051 #以端口50051启动 Restart=always RestartSec=10 KillSignal=SIGINT SyslogIdentifier=myapp User=www-data #启动服务的用户,默认www-data Group=www-data #启动服务的用户组,默认www-data Environment=ASPNETCORE_ENVIRONMENT=Production [Install] WantedBy=multi-user.target
请将 /path/to/your/app 替换为实际的应用程序路径。
2.启用服务: 保存文件后,运行以下命令:
sudo systemctl enable myapp.service sudo systemctl start myapp.service
3.验证服务状态: 使用以下命令检查服务是否正常运行
sudo systemctl status myapp.service
4.测试开机启动: 重启系统后,确认服务是否自动启动:
sudo reboot sudo systemctl status myapp.service
这种方法不仅可以实现开机自动运行,还能在应用崩溃时自动重启,确保服务的高可用性。
5.查看已经运行的服务
#列出所有服务 systemctl list-units --type=service #查看所有服务的状态 service --status-all #列出所有启用的服务 systemctl list-unit-files --state=enabled #查看正在运行的服务 systemctl list-units --type=service --state=running
浙公网安备 33010602011771号