Microsoft MVP성태의 닷넷 이야기
.NET Framework: 681. dotnet.exe - run, exec, build, restore, publish 차이점 [링크 복사], [링크+제목 복사]
조회: 13539
글쓴 사람
정성태 (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
정성태

... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12100정성태1/3/20209115.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202011398디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202010997.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209537디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911546디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201912894VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201911066.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201911108.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910518디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201912046디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
12090정성태12/24/201910633.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [1]파일 다운로드1
12089정성태12/23/201911393디버깅 기술: 146. gflags와 _CrtIsMemoryBlock을 이용한 Heap 메모리 손상 여부 체크
12088정성태12/23/201910350Linux: 28. Linux - 윈도우의 "Run as different user" 기능을 shell에서 실행하는 방법
12087정성태12/21/201910840디버깅 기술: 145. windbg/sos - Dictionary의 entries 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12086정성태12/20/201912879디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201910583오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
12084정성태12/19/201911217디버깅 기술: 143. windbg/sos - Hashtable의 buckets 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12083정성태12/17/201912501Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법 [2]
12082정성태12/17/201912337오류 유형: 585. lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
12081정성태12/16/201914060개발 환경 구성: 465. 로컬 PC에서 개발 중인 ASP.NET Core 웹 응용 프로그램을 다른 PC에서도 접근하는 방법 [5]
12080정성태12/16/201911974.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
12079정성태12/13/201913174오류 유형: 584. 원격 데스크톱(rdp) 환경에서 다중 또는 고용량 파일 복사 시 "Unspecified error" 오류 발생
12078정성태12/13/201913155Linux: 26. .NET Core 응용 프로그램을 위한 메모리 덤프 방법 [3]
12077정성태12/13/201912661Linux: 25. 자주 실행할 명령어 또는 초기 환경을 "~/.bashrc" 파일에 등록
12076정성태12/12/201910857디버깅 기술: 142. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅 - 배포 방법에 따른 차이
12075정성태12/11/201911695디버깅 기술: 141. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...