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

1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13449정성태11/21/20232349개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232621닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232486닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232419닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232699Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232454닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232492개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232321개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232652닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232352Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232842닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232462닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232656닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232893닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232828닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232618스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232341스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232378오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232707스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232597닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232856닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232918닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233085닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233268스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233084닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233063스크립트: 58. 파이썬 - async/await 기본 사용법
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...