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

... 46  47  48  49  50  [51]  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12354정성태10/2/202020730오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202010542개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202011033개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
12351정성태10/2/202010540오류 유형: 659. Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
12350정성태9/25/202014053Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 [2]파일 다운로드1
12349정성태9/25/20209010Linux: 32. Ubuntu 20.04 - docker를 위한 tcp 바인딩 추가
12348정성태9/25/20209694오류 유형: 658. 리눅스 docker - Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
12347정성태9/25/202023864Windows: 174. WSL 2의 네트워크 통신 방법 [4]
12346정성태9/25/20208949오류 유형: 657. IIS - http://localhost 방문 시 Service Unavailable 503 오류 발생
12345정성태9/25/20208680오류 유형: 656. iisreset 실행 시 "Restart attempt failed." 오류가 발생하지만 웹 서비스는 정상적인 경우파일 다운로드1
12344정성태9/25/20209854Windows: 173. 서비스 관리자에 "IIS Admin Service"가 등록되어 있지 않다면?
12343정성태9/24/202019408.NET Framework: 945. C# - 닷넷 응용 프로그램에서 메모리 누수가 발생할 수 있는 패턴 [5]
12342정성태9/24/202010739디버깅 기술: 171. windbg - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법
12341정성태9/23/20209884.NET Framework: 944. C# - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법파일 다운로드1
12340정성태9/23/20209611.NET Framework: 943. WPF - WindowsFormsHost를 담은 윈도우 생성 시 메모리 누수
12339정성태9/21/20209574오류 유형: 655. 코어 모드의 윈도우는 GUI 모드의 윈도우로 교체가 안 됩니다.
12338정성태9/21/20209118오류 유형: 654. 우분투 설치 시 "CHS: Error 2001 reading sector ..." 오류 발생
12337정성태9/21/202010424오류 유형: 653. Windows - Time zone 설정을 바꿔도 반영이 안 되는 경우
12336정성태9/21/202012927.NET Framework: 942. C# - WOL(Wake On Lan) 구현
12335정성태9/21/202022330Linux: 31. 우분투 20.04 초기 설정 - 고정 IP 및 SSH 설치
12334정성태9/21/20207764오류 유형: 652. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter"
12333정성태9/20/20208222.NET Framework: 941. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)
12332정성태9/18/202010248.NET Framework: 940. C# - Windows Forms ListView와 DataGridView의 예제 코드파일 다운로드1
12331정성태9/18/20209410오류 유형: 651. repadmin /syncall - 0x80090322 The target principal name is incorrect.
12330정성태9/18/202010451.NET Framework: 939. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 [2]파일 다운로드1
12329정성태9/16/202012345오류 유형: 650. ASUS 메인보드 관련 소프트웨어 설치 후 ArmouryCrate.UserSessionHelper.exe 프로세스 무한 종료 현상
... 46  47  48  49  50  [51]  52  53  54  55  56  57  58  59  60  ...