在Ubuntu上部署.Net Core

2018/05/19 361

在 Ubuntu 中安装 .Net Core环境

https://www.microsoft.com/net/learn/get-started/windows

将程序打包,放到Ubuntu上运行起来。

有时候,开发环境的SDK版本高于服务器上的,在运行时会报错。 请尝试将服务器上的.Net Core升级

Error:
An assembly specified in the application dependencies manifest (HappyDog.Api.deps.json) was not found:
package: 'Microsoft.AspNetCore.Antiforgery', version: '2.0.3'
path: 'lib/netstandard2.0/Microsoft.AspNetCore.Antiforgery.dll'
This assembly was expected to be in the local runtime store as the application was published using the following target manifest files: aspnetcore-store-2.0.8.xml

当启动正常时会出现以下信息

Hosting environment: Production Content root path: /home/mytos/happydog Now listening on: http://localhost:5000 Application started. Press Ctrl+C to shut down

我们访问 http://localhost:5000 ,但只能本地访问,我们需要一个Nginx代理

安装Nginx

sudo apt-get install nginx

vim /etc/nginx/sites-available/default 编辑Nginx的配置,让它代理 http://localhost:5000

server {
    listen        80;
    server_name   example.com *.example.com;
    location / {
        proxy_pass         http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $http_host;
        proxy_cache_bypass $http_upgrade;
    }
}

运行sudo nginx -t,如果配置文件测试成功,强制Nginx运行新的配置 sudo nginx -s reload

监视应用

服务器已设置为转发到发出的请求http://<serveraddress>:80Kestrel 在上运行 ASP.NET Core 应用到http://127.0.0.1:5000。 但是,Nginx 未设置来管理 Kestrel 过程。 systemd可以用于创建服务文件以启动和监视基础的 web 应用。 systemd 是一个 init 系统,可以提供用于启动、停止和管理进程的许多强大的功能。

创建服务定义文件:
sudo nano /etc/systemd/system/kestrel-hellomvc.service

下面是应用程序的示例服务文件:

[Unit]
Description=Example .NET Web API App running on Ubuntu

[Service]
WorkingDirectory=/var/aspnetcore/hellomvc
ExecStart=/usr/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll
Restart=always
RestartSec=10  # Restart service after 10 seconds if dotnet service crashes
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target
保存该文件并启用该服务
systemctl enable kestrel-hellomvc.service
启动服务并验证它正在运行
systemctl start kestrel-hellomvc.service
systemctl status kestrel-hellomvc.service

● kestrel-hellomvc.service - Example .NET Web API App running on Ubuntu
    Loaded: loaded (/etc/systemd/system/kestrel-hellomvc.service; enabled)
    Active: active (running) since Thu 2016-10-18 04:09:35 NZDT; 35s ago
Main PID: 9021 (dotnet)
    CGroup: /system.slice/kestrel-hellomvc.service
            └─9021 /usr/local/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll

更多请参考微软官方文档

如果需要更新,需要重启 systemctl restart kestrel-hellomvc.service

评论