如何将ASP.NET Core成功部署到Linux服务器上?
摘要:# 如何部署ASP.NET Core 到Linux服务器 我们开发的最终目的,是将开发后的东西发布网络上,以便自己及其他人使用。 本篇博客介绍如果在 linux 上部署 ASP.NET Core应用,使用nginx+sys
如何部署ASP.NET Core 到Linux服务器
我们开发的最终目的,是将开发后的东西发布网络上,以便自己及其他人使用。
本篇博客介绍如果在 linux 上部署 ASP.NET Core应用,使用nginx+systemd 来管理我们的应用。
准备
Ubuntu 20.04
Nginx
.NET SDK 或 Runtime
安装
安装Nginx
安装.NET
配置
配置Nginx
配置文件
nginx默认配置会加载/etc/nginx/sites-enabled中的网站,通常我们并不会在该目录下直接配置网站,而只是定义需要生效网站的软链接,实际定义文件通常在/etc/nginx/sites-available目录去定义。
cd /etc/nginx/sites-availabe
sudo vim my-web
以为下nginx 的配置示例
server {
listen 80;
server_name _;
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 $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
[!TIP]
proxy_pass,意思是用户访问先经过nginx,然后nginx会路由到 proxy_pass 地址,这个地址也就是asp.net core 服务实际运行使用的地址.
让配置文件生效
我们已经在/etc/nginx/sites-available下创建了 my-web配置文件,现在来创建软链接。
cd /etc/nginx/sites-enable
sudo ln -s /etc/nginx/sites-available/my-web ./
接下来我们可以使用nginx -t来测试配置文件是否正确。
最后使用配置文件生效,可使用nginx -s reload来重载nginx的配置,以使新站点配置生效。
sudo nginx -t
sudo nginx -s reload
配置服务以自动启动
systemctl 命令用于管理“服务”或“守护程序”。 守护程序的概念与 Windows 服务的概念类似。 当系统启动时,可以自动重启此类服务。
我们需要将我们的应用配置成服务,这样就可以自动运行。
创建服务文件
在/etc/systemd/system/目录下创建服务文件,
cd /etc/systemd/system/
sudo vim dusi.service
内容如下:
[Unit]
Description=dusi web site
[Service]
WorkingDirectory=/var/dusi/
ExecStart=/usr/bin/dotnet /var/dusi/Http.API.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dusi-log
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
以下是此内容的一些关键方面:
WorkingDirectory 是发布应用程序的目录。
ExecStart 是启动应用程序的实际命令,dotnet 需要指定到使用的dll文件
Restart=always 果由于某种原因(无论是手动还是由于崩溃)而停止,则始终会启动此过程。
