参考官方文档 https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-2.1
Kestrel 是 ASP.NET Core 的默认 web server。Kestrel 是跨平台的 (linux macos windows 上都能运行)。部署时可以直接用 Kestrel 跑。也可以与反向代理服务器(IIS、Nginx、Apache)一起使用。


一般在生产环境中都用反向代理来部署,因为反向代理方便做负载均衡、 SSL 和安全防护等。
下面用 centos7 来演示一下部署
打包发布
dotnet publish --configuration Release
用 detnet 命令行发布。或在 VS 中点击 Build -> Publish 选择发布到文件夹。
下面是发布后的目录结构

之后把打包好的文件压缩上传到服务器。
centos7 中安装 .NET Core runtime
官方文档 https://dotnet.microsoft.com/download/dotnet-core/2.1
.NET Core 有两种安装方式。一可以直接下载官方编译好的二进制文件,然后解压,配置 PATH 就行了。二可以用 Package Manager (yum、 apt-get 等) 自动安装。
下面用 yum 安装
sudo rpm -Uvh https://packages.microsoft.com/config/rhel/7/packages-microsoft-prod.rpm
sudo yum update
sudo yum install aspnetcore-runtime-2.1
上面的命令会同时安装 .NET Core runtime 和 ASP.NET Core runtime。 .NET Core runtime 只能运行 .net core 命令行程序等, ASP.NET Core runtime 能够运行 ASP.NET web 应用。
确保命令行可以正确执行 dotnet
命令。
切换到程序根目录执行 dotnet xxxx.dll
启动程序(xxx 是你 app 的名称),确保程序可以正确启动。

默认启动在 5000 端口,也可以配置为别的端口号
下面安装 nginx 并配置反向代理
首先添加 nginx 的 yum repository, 新建一个文件 /etc/yum.repos.d/nginx.repo
, 把下面的配置拷贝到文件中
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
之后执行
sudo yum install nginx
确保 nginx 成功安装并运行在 80 端口

nginx 默认配置文件是 /etc/nginx/nginx.conf
, 里面默认包含了conf.d 下面的所有配置文件。(include /etc/nginx/conf.d/*.conf;
)
修改 conf.d 目录下默认的 default.conf
文件替换为下面的反向代理配置
server {
listen 80;
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;
}
}
之后执行
nginx -s reload
执行时报了一个
nginx: [error] invalid PID number "" in "/var/run/nginx.pid"
的错误,pkill -9 nginx
杀死进程重启后重新执行 reload 就好了
命令行启动程序, 之后访问 80 端口,发现反向代理已经起作用了。

systemd 做进程管理(也可以用 supervisor)
在 /etc/systemd/system
下面新建一个 kestrel-helloapp.service
文件,把下面的配置拷贝进去
[Unit]
Description=Example .NET Web App running on centos
[Service]
WorkingDirectory=/root/hello/publish
ExecStart=/usr/bin/dotnet /root/hello/publish/WebApplication2.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
enable service
sudo systemctl enable kestrel-helloapp.service
start service 并查看状态
sudo systemctl start kestrel-helloapp.service
sudo systemctl status kestrel-helloapp.service

浏览器访问发现运行成功
查看日志
奔溃或运行失败时需要查看 systemd 的日志
sudo journalctl -fu kestrel-helloapp.service --since "2016-10-18" --until "2016-10-18 04:00"
网友评论