将 ASP.NET Core 从 Visual Studio 发布到 Linux

Posted

技术标签:

【中文标题】将 ASP.NET Core 从 Visual Studio 发布到 Linux【英文标题】:Publish ASP.NET Core from Visual Studio to Linux 【发布时间】:2017-02-15 16:09:41 【问题描述】:

我可以在 Visual Studio 中编辑 ASP.NET Core 应用程序并部署到 Linux 服务器(例如,Ubuntu)吗?

【问题讨论】:

【参考方案1】:

您可以在 ASP.NET CORE 文档中查看此页面 - https://docs.microsoft.com/en-us/aspnet/core/publishing/linuxproduction

也可以在 Scott Hanselman 的这篇博文中找到一个很好的例子 - https://www.hanselman.com/blog/PublishingAnASPNETCoreWebsiteToACheapLinuxVMHost.aspx

我目前使用自己的批处理脚本进行部署,步骤如下:

    使用 dotnet publish 命令发布应用程序。 使用 Powershell 压缩所有内容。 使用 pscp 将 zip 复制到 Linux 机器 - https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html 使用 Windows Bash 连接到 Linux 计算机(您需要 Windows 10 周年更新才能使用此功能)。 在 Linux 机器上调用 unzip 命令 - 需要先安装在那里。 在 Linux 机器上重新启动主管服务。

编辑: 我添加了我在按照Andrew Basarab 的要求发布原始答案时使用的脚本版本。考虑到我当时糟糕的脚本知识,我确信它需要一些重构。请谨慎使用:

@echo off

set PrivateKeyLocation="C:\fakepath\fakefile.ppk private key for connecting to the remote Linux machine"
set CertificateFileLocation="/mnt/c/fakepath/fakefile.pem same key used to execute remote bash commands from my Windows machine"

for %%* in (.) do set CurrentDirName=%%~nx*
set OutputFolder="%tmp%\%CurrentDirName%"
set OutputZipFile="%tmp%\%CurrentDirName%.zip"
set RemoteHost="ubuntu@54.142.181.122 remote host address"
set RemoteLocation="/home/ubuntu the location to copy the output to"

dotnet publish -o "%OutputFolder%"

powershell -command "& &'Compress-Archive' -Path %OutputFolder% -DestinationPath %OutputZipFile%"
rmdir /s /q %OutputFolder%

pscp -i %PrivateKeyLocation% -pw private key password %OutputZipFile% %RemoteHost%:%RemoteLocation%
del /q %OutputZipFile%

bash -c "ssh -i %CertificateFileLocation% %RemoteHost% 'sudo rm -rf %CurrentDirName% ; unzip %CurrentDirName%.zip ; rm -r %CurrentDirName%.zip ; sudo service supervisor restart'"

需要在两台机器上安装一些工具和服务。请参考上述 Scott Hanselman 的帖子。

【讨论】:

你能分享你的 bash 脚本吗?我有同样的需求,目前使用 WinSCP 手动完成所有这些步骤需要花费大量时间。 @AndrewBasarab,我刚刚将脚本添加到我的答案帖子中。我很久以前就这样做了,不太记得细节,所以请谨慎使用该脚本。【参考方案2】:

我不知道您如何将 Visual Studio 部署到 Ubuntu 服务器,但如果您可以访问服务器(例如使用 SSH),您可以简单地从 Git 的存储库中提取代码,然后编译、发布并运行。

【讨论】:

以上是关于将 ASP.NET Core 从 Visual Studio 发布到 Linux的主要内容,如果未能解决你的问题,请参考以下文章