1. 首先在/etc/systemd/system/目录下添加如下文件
vi example.service
[Unit]
Description=example running on Ubuntu
# 如果有依赖和先后执行顺序要加上以下的
Requires=mysql.service
After=mysql.service
# Before=mysql.service
[Service]
# 发布应用程序的目录
WorkingDirectory=/var/web/example
# 启动应用程序的命令
ExecStart=dotnet /var/web/example/example.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
# 系统日志标识符
SyslogIdentifier=example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
应用程序目录对www-data用户要有相应的权限
chown -R www-data:www-data /var/web/example
chmod -R 775 /var/web/example
常用的linux文件权限:
444 r--r--r--
600 rw-------
644 rw-r--r--
666 rw-rw-rw-
700 rwx------
744 rwxr--r--
755 rwxr-xr-x
777 rwxrwxrwx
2. 运行服务
sudo systemctl start myfirstwebapp.service
3. 启用服务
上面步骤运行服务后,如果关机,服务不会自动启动,运行以下命令才会每次开机自动运行服务
sudo systemctl enable myfirstwebapp.service
# 也可以加上这个命令,在配置好服务后立即启动
sudo systemctl enable myfirstwebapp.service --now
4. 查看服务运行状态
systemctl status example.service
# 查看实时日志
journalctl -fu example.service
最后:
如果改了服务配置文件,要记得运行命令
# 停止服务,要改配置时,先停止服务
systemctl stop example.service
# 改好后,重新加载配置
systemctl daemon-reload
# 重启服务或启动服务
systemctl start example.service
systemctl restart example.service
坑:
如果Ubuntu下用snap装的dotnet运行环境,snap好像是将dotnet工具包装了下,但是有些权限是不足的,如果直接用/snap/bin/dotnet是不行的,可以找到dotnet命令的真正位置,然后填上
如下:
[Unit]
Description=example running on Ubuntu
# 如果有依赖和先后执行顺序要加上以下的
Requires=mysql.service
After=mysql.service
# Before=mysql.service
[Service]
# 发布应用程序的目录
WorkingDirectory=/var/web/example
# 启动应用程序的命令
ExecStart=/snap/dotnet-sdk/254/dotnet /var/web/example/example.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
# 系统日志标识符
SyslogIdentifier=example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target