Microsoft MVP성태의 닷넷 이야기
.NET Framework: 681. dotnet.exe - run, exec, build, restore, publish 차이점 [링크 복사], [링크+제목 복사]
조회: 13495
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

dotnet.exe - run, exec, build, restore, publish 차이점

dotnet.exe의 실행 옵션이 매우 다양해서 다소 혼란스러울 수 있는데요.

우선, dotnet.exe를 이용해 실행이 될 DLL을 아무런 옵션 없이 지정해 실행하는 것이 가능합니다. 예를 들어, Console App 프로젝트를 만들고 ConsoleApp1.dll이 생성되었다면 다음과 같이 실행할 수 있습니다.

dotnet "c:\temp\ConsoleApp1\bin\Debug\netcoreapp2.0\ConsoleApp1.dll"

그리고, 실행한다는 옵션인 exec를 명시적으로 지정하는 것도 가능합니다.

dotnet exec "c:\temp\ConsoleApp1\bin\Debug\netcoreapp2.0\ConsoleApp1.dll"

즉, exec를 빼거나 넣는 것은 아무런 차이가 없습니다. 이걸 어떻게 아냐고요? ^^ 다음과 같은 환경 변수를 두면 dotnet.exe의 동작을 살펴볼 수 있기 때문입니다.

SET COREHOST_TRACE=1

이 옵션을 켜고 dotnet / dotnet exec를 실행해 살펴보면 동일한 결과를 확인할 수 있습니다. (참고로, Visual Studio에서도 exec 옵션을 넣어 실행합니다.)




그럼 나머지 옵션을 알아볼까요?

우선 "dotnet run"은 다음과 같습니다.

"dotnet run" == "dotnet build" + "dotnet exec"

그리고 실행 시 exec처럼 dll 경로 없이 .csproj가 있는 폴더에서 다음과 같이 실행하면 됩니다.

C:\temp\ConsoleApp1>dotnet run

특이하게도 "dotnet run"으로 인해 "dotnet.exe"가 주 프로세스로 우선 실행되고 그 프로세스의 하위로 build 작업과 "dotnet exec"를 순서대로 실행합니다. 즉 프로세스 구조가 이렇게 되는 것입니다.

dotnet run
    => [build]
    => dotnet exec "c:\temp\ConsoleApp1\bin\Debug\netcoreapp2.0\ConsoleApp1.dll"

위의 [build] 과정은 독립적으로 "dotnet build"로 실행하는 것도 가능합니다. 이름에서 의미하듯이 그냥 빌드만 하는 것으로 역시 인자는 더 필요 없고 .csproj 파일이 있는 폴더에서 실행하면 됩니다.

C:\temp\ConsoleApp1>dotnet build             

그런데 다음의 문서에 보면,

dotnet-build
; https://docs.microsoft.com/en-us/dotnet/core/tutorials/using-with-xplat-cli

.NET 1.x에서는 build만 수행했던 반면, .NET 2.0부터는 restore 동작까지 수행하도록 바뀌었습니다.

dotnet build
 == 1.x) build
 == 2.0) restore + build

여기서 "dotnet restore" 역시 독립적으로 .csproj 파일이 있는 폴더에서 실행할 수 있습니다.

C:\temp\ConsoleApp1>dotnet restore             

그럼 .csproj의 정보를 읽어 의존성을 파악 후 NuGet으로부터 빌드에 필요한 패키지들을 내려받게 됩니다.

재미있는 것은, "restore"와 "build"도 (.NET Core 2.0의 경우) 다음과 같이 msbuild.dll을 "dotnet exec"로 실행하는 형식입니다.

=== dotnet restore ===
"dotnet.exe" exec "C:\Program Files (x86)\dotnet\sdk\2.0.0\MSBuild.dll" /m /v:m /NoLogo /t:Restore /verbosity:q c:\temp\ConsoleApp1\ConsoleApp1.csproj "/Logger:Microsoft.DotNet.Tools.MSBuild.MSBuildLogger,C:\Program Files (x86)\dotnet\sdk\2.0.0\dotnet.dll"

=== dotnet build ===
"dotnet.exe" exec "C:\Program Files (x86)\dotnet\sdk\2.0.0\MSBuild.dll" /m /v:m c:\temp\ConsoleApp1\ConsoleApp1.csproj /nologo /verbosity:quiet "/Logger:Microsoft.DotNet.Tools.MSBuild.MSBuildLogger,C:\Program Files (x86)\dotnet\sdk\2.0.0\dotnet.dll"

다시 dotnet build는 Roslyn 컴파일러를 자식 프로세스로 다음과 같은 형식으로 실행합니다.

C:\Windows\system32\cmd.exe /c ""C:\Program Files (x86)\dotnet\sdk\2.0.0\Roslyn\RunCsc.cmd"  /noconfig @"%LOCALAPPDATA%\Temp\tmp16a0b2df706f43dabe1aff5b84dd270b.rsp""
  ==> [call] "C:\Program Files (x86)\dotnet\sdk\2.0.0\Roslyn\..\..\..\dotnet"  "C:\Program Files (x86)\dotnet\sdk\2.0.0\Roslyn\csc.exe" /noconfig @"%LOCALAPPDATA%\Temp\tmp16a0b2df706f43dabe1aff5b84dd270b.rsp"




사실 위의 모든 상황은 개발자 PC에서만 유효한 것들입니다. 왜냐하면 실행에 필요한 의존성을 갖는 DLL들이 모두 로컬 PC의 NuGet 폴더에 있기 때문입니다. 즉, 다른 PC에서는 실행이 안될 수 있습니다.

다른 PC에서도 실행할 수 있도록 만들고 싶다면 "dotnet publish"를 실행해 의존성을 모두 해결한 바이너리 묶음을 얻으면 됩니다. 그래서 쓸 수 있는 옵션이 "dotnet publish"입니다.

이 옵션도 역시 .csproj 파일이 있는 폴더에서 실행하면 됩니다.

C:\temp\ConsoleApp1>dotnet publish

그럼, 모든 의존성을 파악하고 /publish 폴더에 파일들을 출력합니다. 가령, 기본 코드만 있는 ConsoleApp을 만들어 publish하면 이렇게 4개의 파일이 출력됩니다.

  • ConsoleApp1.deps.json
  • ConsoleApp1.dll
  • ConsoleApp1.pdb
  • ConsoleApp1.runtimeconfig.json

(기본 코드만 있기 때문에 의존성이 없어 이런 경우에는 /bin/Debug에 있는 파일로도 배포할 수 있습니다.)

재미있는 것은, 별다른 의존성이 없는데도 ConsoleApp1.dll만 다른 컴퓨터로 복사해 "dotnet [exec]"로 실행하면 다음과 같은 오류가 발생한다는 점입니다.

C:\temp>dotnet ConsoleApp1.dll
A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in 'C:\temp\'.

왜냐하면, ConsoleApp1.runtimeconfig.json 파일이 꼭 필요하기 때문입니다. 그래서 적어도 다음의 2개 파일은 꼭 있어야 실행이 가능합니다.

  • ConsoleApp1.dll
  • ConsoleApp1.runtimeconfig.json

참고로 ConsoleApp1.runtimeconfig.json 파일의 내용은 이렇습니다.

{
  "runtimeOptions": {
    "tfm": "netcoreapp2.0",
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "2.0.0"
    }
  }
}

어쨌든, 그냥 간단하게 다른 PC로 배포해야 할 때는 publish로 출력된 내용을 모두 복사하는 것이 마음 편합니다. 그런데 publish 옵션에 더 재미있는 기능이 있습니다.

.NET Core 1.1 - How to publish a self-contained application
; https://blogs.msdn.microsoft.com/luisdem/2017/03/19/net-core-1-1-how-to-publish-a-self-contained-application/

즉, .csproj 파일에 RuntimeIdentifiers 옵션을 추가해,

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <RuntimeIdentifiers>win10-x64</RuntimeIdentifiers>
  </PropertyGroup>

</Project>

이렇게 publish를 해주면,

dotnet publish -c release -r win10-x64

[dll이름].exe 파일이 출력되어 곧바로 ConsoleApp1.exe로 실행할 수 있습니다. 게다가 모든 의존성이 x64 용으로 빌드되어 심지어 dotnet core runtime이 설치되지 않은 환경에서도 실행할 수 있습니다. 그런데, 파일이 무려 215개나 됩니다. ^^;

api-ms-win-core-console-l1-1-0.dll
api-ms-win-core-datetime-l1-1-0.dll
api-ms-win-core-debug-l1-1-0.dll
api-ms-win-core-errorhandling-l1-1-0.dll
api-ms-win-core-file-l1-1-0.dll
api-ms-win-core-file-l1-2-0.dll
api-ms-win-core-file-l2-1-0.dll
api-ms-win-core-handle-l1-1-0.dll
api-ms-win-core-heap-l1-1-0.dll
api-ms-win-core-interlocked-l1-1-0.dll
api-ms-win-core-libraryloader-l1-1-0.dll
api-ms-win-core-localization-l1-2-0.dll
api-ms-win-core-memory-l1-1-0.dll
api-ms-win-core-namedpipe-l1-1-0.dll
api-ms-win-core-processenvironment-l1-1-0.dll
api-ms-win-core-processthreads-l1-1-0.dll
api-ms-win-core-processthreads-l1-1-1.dll
api-ms-win-core-profile-l1-1-0.dll
api-ms-win-core-rtlsupport-l1-1-0.dll
api-ms-win-core-string-l1-1-0.dll
api-ms-win-core-synch-l1-1-0.dll
api-ms-win-core-synch-l1-2-0.dll
api-ms-win-core-sysinfo-l1-1-0.dll
api-ms-win-core-timezone-l1-1-0.dll
api-ms-win-core-util-l1-1-0.dll
api-ms-win-crt-conio-l1-1-0.dll
api-ms-win-crt-convert-l1-1-0.dll
api-ms-win-crt-environment-l1-1-0.dll
api-ms-win-crt-filesystem-l1-1-0.dll
api-ms-win-crt-heap-l1-1-0.dll
api-ms-win-crt-locale-l1-1-0.dll
api-ms-win-crt-math-l1-1-0.dll
api-ms-win-crt-multibyte-l1-1-0.dll
api-ms-win-crt-private-l1-1-0.dll
api-ms-win-crt-process-l1-1-0.dll
api-ms-win-crt-runtime-l1-1-0.dll
api-ms-win-crt-stdio-l1-1-0.dll
api-ms-win-crt-string-l1-1-0.dll
api-ms-win-crt-time-l1-1-0.dll
api-ms-win-crt-utility-l1-1-0.dll
clrcompression.dll
clretwrc.dll
clrjit.dll
ConsoleApp1.deps.json
ConsoleApp1.dll
ConsoleApp1.exe
ConsoleApp1.pdb
ConsoleApp1.runtimeconfig.json
coreclr.dll
dbgshim.dll
hostfxr.dll
hostpolicy.dll
Microsoft.CSharp.dll
Microsoft.DiaSymReader.Native.amd64.dll
Microsoft.VisualBasic.dll
Microsoft.Win32.Primitives.dll
Microsoft.Win32.Registry.dll
mscordaccore.dll
mscordaccore_amd64_amd64_4.6.00001.0.dll
mscordbi.dll
mscorlib.dll
mscorrc.debug.dll
mscorrc.dll
netstandard.dll
sos.dll
SOS.NETCore.dll
sos_amd64_amd64_4.6.00001.0.dll
System.AppContext.dll
System.Buffers.dll
System.Collections.Concurrent.dll
System.Collections.dll
System.Collections.Immutable.dll
System.Collections.NonGeneric.dll
System.Collections.Specialized.dll
System.ComponentModel.Annotations.dll
System.ComponentModel.Composition.dll
System.ComponentModel.DataAnnotations.dll
System.ComponentModel.dll
System.ComponentModel.EventBasedAsync.dll
System.ComponentModel.Primitives.dll
System.ComponentModel.TypeConverter.dll
System.Configuration.dll
System.Console.dll
System.Core.dll
System.Data.Common.dll
System.Data.dll
System.Diagnostics.Contracts.dll
System.Diagnostics.Debug.dll
System.Diagnostics.DiagnosticSource.dll
System.Diagnostics.FileVersionInfo.dll
System.Diagnostics.Process.dll
System.Diagnostics.StackTrace.dll
System.Diagnostics.TextWriterTraceListener.dll
System.Diagnostics.Tools.dll
System.Diagnostics.TraceSource.dll
System.Diagnostics.Tracing.dll
System.dll
System.Drawing.dll
System.Drawing.Primitives.dll
System.Dynamic.Runtime.dll
System.Globalization.Calendars.dll
System.Globalization.dll
System.Globalization.Extensions.dll
System.IO.Compression.dll
System.IO.Compression.FileSystem.dll
System.IO.Compression.ZipFile.dll
System.IO.dll
System.IO.FileSystem.AccessControl.dll
System.IO.FileSystem.dll
System.IO.FileSystem.DriveInfo.dll
System.IO.FileSystem.Primitives.dll
System.IO.FileSystem.Watcher.dll
System.IO.IsolatedStorage.dll
System.IO.MemoryMappedFiles.dll
System.IO.Pipes.dll
System.IO.UnmanagedMemoryStream.dll
System.Linq.dll
System.Linq.Expressions.dll
System.Linq.Parallel.dll
System.Linq.Queryable.dll
System.Net.dll
System.Net.Http.dll
System.Net.HttpListener.dll
System.Net.Mail.dll
System.Net.NameResolution.dll
System.Net.NetworkInformation.dll
System.Net.Ping.dll
System.Net.Primitives.dll
System.Net.Requests.dll
System.Net.Security.dll
System.Net.ServicePoint.dll
System.Net.Sockets.dll
System.Net.WebClient.dll
System.Net.WebHeaderCollection.dll
System.Net.WebProxy.dll
System.Net.WebSockets.Client.dll
System.Net.WebSockets.dll
System.Numerics.dll
System.Numerics.Vectors.dll
System.ObjectModel.dll
System.Private.CoreLib.dll
System.Private.DataContractSerialization.dll
System.Private.Uri.dll
System.Private.Xml.dll
System.Private.Xml.Linq.dll
System.Reflection.DispatchProxy.dll
System.Reflection.dll
System.Reflection.Emit.dll
System.Reflection.Emit.ILGeneration.dll
System.Reflection.Emit.Lightweight.dll
System.Reflection.Extensions.dll
System.Reflection.Metadata.dll
System.Reflection.Primitives.dll
System.Reflection.TypeExtensions.dll
System.Resources.Reader.dll
System.Resources.ResourceManager.dll
System.Resources.Writer.dll
System.Runtime.CompilerServices.VisualC.dll
System.Runtime.dll
System.Runtime.Extensions.dll
System.Runtime.Handles.dll
System.Runtime.InteropServices.dll
System.Runtime.InteropServices.RuntimeInformation.dll
System.Runtime.InteropServices.WindowsRuntime.dll
System.Runtime.Loader.dll
System.Runtime.Numerics.dll
System.Runtime.Serialization.dll
System.Runtime.Serialization.Formatters.dll
System.Runtime.Serialization.Json.dll
System.Runtime.Serialization.Primitives.dll
System.Runtime.Serialization.Xml.dll
System.Security.AccessControl.dll
System.Security.Claims.dll
System.Security.Cryptography.Algorithms.dll
System.Security.Cryptography.Cng.dll
System.Security.Cryptography.Csp.dll
System.Security.Cryptography.Encoding.dll
System.Security.Cryptography.OpenSsl.dll
System.Security.Cryptography.Primitives.dll
System.Security.Cryptography.X509Certificates.dll
System.Security.dll
System.Security.Principal.dll
System.Security.Principal.Windows.dll
System.Security.SecureString.dll
System.ServiceModel.Web.dll
System.ServiceProcess.dll
System.Text.Encoding.dll
System.Text.Encoding.Extensions.dll
System.Text.RegularExpressions.dll
System.Threading.dll
System.Threading.Overlapped.dll
System.Threading.Tasks.Dataflow.dll
System.Threading.Tasks.dll
System.Threading.Tasks.Extensions.dll
System.Threading.Tasks.Parallel.dll
System.Threading.Thread.dll
System.Threading.ThreadPool.dll
System.Threading.Timer.dll
System.Transactions.dll
System.Transactions.Local.dll
System.ValueTuple.dll
System.Web.dll
System.Web.HttpUtility.dll
System.Windows.dll
System.Xml.dll
System.Xml.Linq.dll
System.Xml.ReaderWriter.dll
System.Xml.Serialization.dll
System.Xml.XDocument.dll
System.Xml.XmlDocument.dll
System.Xml.XmlSerializer.dll
System.Xml.XPath.dll
System.Xml.XPath.XDocument.dll
ucrtbase.dll
WindowsBase.dll

플랫폼 별로 RuntimeIdentifiers를 이런 식으로 설정하는 것도 가능하다고 합니다.

<RuntimeIdentifiers>win10-x64;osx.10.11-x64;ubuntu.16.10-x64</RuntimeIdentifiers>

그리고 개별 환경을 위해 publish를 할 수 있고.

dotnet publish -c release -r ubuntu.16.10-x64
dotnet publish -c release -r osx.10.11-x64

이 정도면 dotnet.exe 관련 옵션들이 눈에 들어오겠죠! ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2020]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2018-05-11 06시39분
정성태
2019-03-06 10시02분
정성태
2021-01-24 09시07분
dotnet publish --self-contained -r win-x64

dotnet publish -f net 5.0 -p:PublishSingleFile=true -r win-x64
dotnet publish -f net 5.0 -p:PublishSingleFile=true -r win-x64 -p:PublishTrimmed=true -p:TrimMode=Link

dotnet publish -f net 5.0 -p:PublishReadyToRun=true -r win-x64

Publish .NET Core apps with the .NET Core CLI
; https://docs.microsoft.com/en-us/dotnet/core/deploying/deploy-with-cli
정성태

... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...
NoWriterDateCnt.TitleFile(s)
12527정성태2/1/20219698개발 환경 구성: 533. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 리눅스 환경파일 다운로드1
12526정성태2/1/20217556개발 환경 구성: 532. Azure Devops의 파이프라인 빌드 시 snk 파일 다루는 방법 - Secure file
12525정성태2/1/20217257개발 환경 구성: 531. Azure Devops - 파이프라인 실행 시 빌드 이벤트를 생략하는 방법
12524정성태1/31/20218300개발 환경 구성: 530. 기존 github 프로젝트를 Azure Devops의 빌드 Pipeline에 연결하는 방법 [1]
12523정성태1/31/20218311개발 환경 구성: 529. 기존 github 프로젝트를 Azure Devops의 Board에 연결하는 방법
12522정성태1/31/20219807개발 환경 구성: 528. 오라클 클라우드의 리눅스 VM - 9000 MTU Jumbo Frame 테스트
12521정성태1/31/20219846개발 환경 구성: 527. 이더넷(Ethernet) 환경의 TCP 통신에서 MSS(Maximum Segment Size) 확인 [1]
12520정성태1/30/20218339개발 환경 구성: 526. 오라클 클라우드의 VM에 ping ICMP 여는 방법
12519정성태1/30/20217469개발 환경 구성: 525. 오라클 클라우드의 VM을 외부에서 접근하기 위해 포트 여는 방법
12518정성태1/30/202124914Linux: 37. Ubuntu에 Wireshark 설치 [2]
12517정성태1/30/202112489Linux: 36. 윈도우 클라이언트에서 X2Go를 이용한 원격 리눅스의 GUI 접속 - 우분투 20.04
12516정성태1/29/20219155Windows: 188. Windows - TCP default template 설정 방법
12515정성태1/28/202110361웹: 41. Microsoft Edge - localhost에 대해 http 접근 시 무조건 https로 바뀌는 문제 [3]
12514정성태1/28/202110656.NET Framework: 1021. C# - 일렉트론 닷넷(Electron.NET) 소개 [1]파일 다운로드1
12513정성태1/28/20218673오류 유형: 698. electronize - User Profile 디렉터리에 공백 문자가 있는 경우 빌드가 실패하는 문제 [1]
12512정성태1/28/20218483오류 유형: 697. The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fix this problem.
12511정성태1/27/20218234Windows: 187. Windows - 도스 시절의 8.3 경로를 알아내는 방법
12510정성태1/27/20218606.NET Framework: 1020. .NET Core Kestrel 호스팅 - Razor 지원 추가 [1]파일 다운로드1
12509정성태1/27/20219560개발 환경 구성: 524. Jupyter Notebook에서 C#(F#, PowerShell) 언어 사용을 위한 환경 구성 [3]
12508정성태1/27/20218169개발 환경 구성: 523. Jupyter Notebook - Slide 플레이 버튼이 없는 경우
12507정성태1/26/20218275VS.NET IDE: 157. Visual Studio - Syntax Visualizer 메뉴가 없는 경우
12506정성태1/25/202111528.NET Framework: 1019. Microsoft.Tye 기본 사용법 소개 [1]
12505정성태1/23/20219314.NET Framework: 1018. .NET Core Kestrel 호스팅 - Web API 추가 [1]파일 다운로드1
12504정성태1/23/202110422.NET Framework: 1017. .NET 5에서의 네트워크 라이브러리 개선 (2) - HTTP/2, HTTP/3 관련 [1]
12503정성태1/21/20218715오류 유형: 696. C# - HttpClient: Requesting HTTP version 2.0 with version policy RequestVersionExact while HTTP/2 is not enabled.
12502정성태1/21/20219469.NET Framework: 1016. .NET Core HttpClient의 HTTP/2 지원파일 다운로드1
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...