目标
windows上开发的dotnet core程序并部署至linux服务器上(Ubuntu 18.04)
步骤
Windows开发
使用Visual Studio2019 创建asp.net core
空白项目,创建项目时,选择dotnet core
版本选择5.0
(Linux服务器中安装的dotnet core runtime
版本也是这个)。
简单创建个HomeController
,两个Action(Index、UserList)
,View
目录下准备两个视图来呈现。UserList
用来显示模拟出来的数据。
创建项目并完成开发
发布
使用VS2019自带发布工具,项目右键选择发布,目标选择文件夹。选好发布存放路径后,配置发布方式目标运行时、部署方式。
两种部署方式的区别在于:
- 独立应用 自带
dotnet
运行时,可以部署至一台空白环境服务器,无需提前安装配置dotnet
运行时。缺点部署包较大。 - 框架依赖型 生成跨平台的部署包,用户只需要安装运行时即可。
接下来将发布出来的文件拷贝至Linux服务器中,使用WinSCP工具拷贝至服务器指定目录上即可。
Linux部署
先决条件
- 安装
dotnet core
, 运行dotnet
程序必备条件(必须) - 安装
supervisor
守护进程,可以帮助你自动启动站点(非必须) - 安装
nginx
做代理 (非必须)
部署步骤
- 安装
dotnet core
sudo apt-get install dotnet-sdk-5.0 --安装5.0sdk
sudo apt-get install dotnet-runtime-5.0 --安装5.0runtime
cd ~/aspnetcoreforlinux
dotnet run aspnetcoreforlinux -- 此时访问localhost:5000已经可以了
- 安装
supervisor
sudo apt-get install supervisor --安装supervisor
//重新加载配置
sudo supervisorctl shutdown && sudo supervisord -c /etc/supervisor/supervisord.conf
//或重启supervisor
sudo service supervisor stop
sudo service supervisor start
为dotnet
项目创建配置文件,进入/etc/supervisor/conf.d
,新建一个config
文件,添加下面的配置文件。注意,目录就是我们从windows上拷贝过来存放的目录。
//新建
sudo touch aspnetcoreforlinux.conf
//aspnetcoreforlinux.conf 添加如下内容
[program:aspnetcoreforlinux]
command=dotnet aspnetcoreforlinux.dll
directory=/home/gxwang/aspnetcoreforlinux
environment=ASPNETCORE__ENVIRONMENT=Production
user=www-data
stopsignal=INT
autostart=true
autorestart=true
startsecs=1
stderr_logfile=/var/log/aspnetcoreforlinux.err.log
stdout_logfile=/var/log/aspnetcoreforlinux.out.log
supervisor
开启web端管理,在/etc/supervisor
目录下,打开supervisor.conf
文件,添加如下配置项
[inet_http_server] ;HTTP服务器,提供web管理界面
port=127.0.0.1:9001 ;访问方式IP+端口
username=admin ;登录时需要身份验证的话,添加用户名和密码
password=admin123
这个时候,点击项目名称连接,可以查看日志。后面的操作可以重启、关闭应用,清除应用日志。关于日志记录位置,上面的配置文件中,我把日志记录在/var/log
目录下了。
- 安装
nginx
sudo apt-get install nginx --安装nginx
sudo vi /etc/nginx/sites-available/default --打开nginx配置文件进行配置
#default配置文件下,增加一个虚拟主机,可以使用同一台机器监听不同端口
# another virtual host using mix of IP-, name-, and port-based configuration
#
server {
listen 80;
# listen somename:8080;
# server_name somename alias another.alias;
# root html;
# index index.html index.htm;
#
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配置后重新加载配置文件
sudo nginx -t
sudo nginx -s reload
备注:安装nginx
时,使用sudo
未能成功,有几个包还会报权限不足。使用su
命令,直接切换到管理员账户来安装即可。
复盘
至此,在windows
上开发好的aspnet core项目部署到ubuntu
上就已经完成了。事实上,关于supervisor
和nginx
并不是必须的。当我们将服务器中安装了dotnet core
运行时,再将发布好的项目文件拷贝到服务器中。使用dotnet run projectname
的方式,就可以运行项目了。这个时候访问项目的地址为localhost:5000
。我们在创建项目时,Properties
目录下的launchSettings.json
中有启动地址的设置。