Microsoft MVP성태의 닷넷 이야기
.NET Framework: 681. dotnet.exe - run, exec, build, restore, publish 차이점 [링크 복사], [링크+제목 복사]
조회: 13330
글쓴 사람
정성태 (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)
12543정성태2/26/20219607VS.NET IDE: 158. C# - 디자인 타임(design-time)과 런타임(runtime)의 코드 실행 구분
12542정성태2/20/202111921개발 환경 구성: 544. github repo의 Release 활성화 및 Actions를 이용한 자동화 방법 [1]
12541정성태2/18/20219179개발 환경 구성: 543. 애저듣보잡 - Github Workflow/Actions 소개
12540정성태2/17/20219505.NET Framework: 1024. C# - Win32 API에 대한 P/Invoke를 대신하는 Microsoft.Windows.CsWin32 패키지
12539정성태2/16/20219381Windows: 189. WM_TIMER의 동작 방식 개요파일 다운로드1
12538정성태2/15/20219794.NET Framework: 1023. C# - GC 힙이 아닌 Native 힙에 인스턴스 생성 - 0SuperComicLib.LowLevel 라이브러리 소개 [2]
12537정성태2/11/202110740.NET Framework: 1022. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서! - 두 번째 이야기 [2]
12536정성태2/9/20219782개발 환경 구성: 542. BDP(Bandwidth-delay product)와 TCP Receive Window
12535정성태2/9/20218911개발 환경 구성: 541. Wireshark로 확인하는 LSO(Large Send Offload), RSC(Receive Segment Coalescing) 옵션
12534정성태2/8/20219550개발 환경 구성: 540. Wireshark + C/C++로 확인하는 TCP 연결에서의 closesocket 동작 [1]파일 다운로드1
12533정성태2/8/20219188개발 환경 구성: 539. Wireshark + C/C++로 확인하는 TCP 연결에서의 shutdown 동작파일 다운로드1
12532정성태2/6/20219718개발 환경 구성: 538. Wireshark + C#으로 확인하는 ReceiveBufferSize(SO_RCVBUF), SendBufferSize(SO_SNDBUF) [3]
12531정성태2/5/20218669개발 환경 구성: 537. Wireshark + C#으로 확인하는 PSH flag와 Nagle 알고리듬파일 다운로드1
12530정성태2/4/202112799개발 환경 구성: 536. Wireshark + C#으로 확인하는 TCP 통신의 Receive Window
12529정성태2/4/20219939개발 환경 구성: 535. Wireshark + C#으로 확인하는 TCP 통신의 MIN RTO [1]
12528정성태2/1/20219301개발 환경 구성: 534. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 윈도우 환경
12527정성태2/1/20219534개발 환경 구성: 533. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 리눅스 환경파일 다운로드1
12526정성태2/1/20217438개발 환경 구성: 532. Azure Devops의 파이프라인 빌드 시 snk 파일 다루는 방법 - Secure file
12525정성태2/1/20217123개발 환경 구성: 531. Azure Devops - 파이프라인 실행 시 빌드 이벤트를 생략하는 방법
12524정성태1/31/20218190개발 환경 구성: 530. 기존 github 프로젝트를 Azure Devops의 빌드 Pipeline에 연결하는 방법 [1]
12523정성태1/31/20218168개발 환경 구성: 529. 기존 github 프로젝트를 Azure Devops의 Board에 연결하는 방법
12522정성태1/31/20219679개발 환경 구성: 528. 오라클 클라우드의 리눅스 VM - 9000 MTU Jumbo Frame 테스트
12521정성태1/31/20219696개발 환경 구성: 527. 이더넷(Ethernet) 환경의 TCP 통신에서 MSS(Maximum Segment Size) 확인 [1]
12520정성태1/30/20218207개발 환경 구성: 526. 오라클 클라우드의 VM에 ping ICMP 여는 방법
12519정성태1/30/20217365개발 환경 구성: 525. 오라클 클라우드의 VM을 외부에서 접근하기 위해 포트 여는 방법
12518정성태1/30/202124777Linux: 37. Ubuntu에 Wireshark 설치 [2]
... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...