Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

윈도우 10에서 .NET Core 응용 프로그램을 리눅스 환경에서 실행하는 2가지 방법 - docker, WSL 2

.NET Core가 리눅스까지 지원하다 보니, 가끔 리눅스 환경의 실행을 확인해야 할 때가 있습니다. 예를 들어 다음의 글을 쓸 때 그랬는데요.

리눅스 환경의 .NET Core에서 "test".IndexOf("")가 0을 반환
; https://www.sysnet.pe.kr/2/0/12237

근래에는 저런 환경이 필요했을 때 가장 쉬운 방법으로 "Docker"를 이용했었습니다.

.NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/12197

그런데, 오늘 날짜로 더 쉬운 방법을 마이크로소프트가 공개했군요. ^^

.NET Core Debugging with WSL 2 - Preview
; https://marketplace.visualstudio.com/items?itemName=ms-azuretools.Dot-Net-Core-Debugging-With-Wsl2

그래서 단순히, 비주얼 스튜디오에서 닷넷 프로젝트를 디버깅하는 경우 실행 환경만 다음과 같이 "WSL 2"로 바꿔주면 됩니다.

wsl2_profile_option_1.png

만약 아직 윈도우 운영체제에 기존 WSL 환경만 있고 "WSL 2" 환경이 없다면 다음과 같이 "--set-version" 명령을 이용해 기존 설치된 배포본을 "WSL 2" 모드로 전환할 수 있습니다.

C:\temp> wsl --list -v
  NAME                   STATE           VERSION
* Ubuntu-20.04           Stopped         1

C:\temp> wsl --set-version Ubuntu-20.04 2
Conversion in progress, this may take a few minutes...
For information on key differences with WSL 2 please visit https://aka.ms/wsl2
Conversion complete.

C:\temp> wsl --list -v
  NAME                   STATE           VERSION
* Ubuntu-20.04           Stopped         2




참고로, WSL 2 환경으로 실행했을 때 대상 WSL 2 배포본에 아직 .NET Core 런타임이 설치되어 있지 않다면 다음과 같은 메시지 창이 뜹니다.

Error launching

.Net Core 3.1 is not installed in the default WSL 2 distribution

Select OK to Install, or Cancel to abort.

OK 버튼을 누르면 자동으로 shell 창이 하나 떠 다음과 같은 명령을 수행하면서 대상 리눅스 배포본에 .NET Core가 설치되는데,

C:\WINDOWS\System32\bash.exe -c "'/mnt/c/USERS/TESTUSR/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/16.0_898C74B1/EXTENSIONS/5YKPGVGM.BZA/Scripts/InstallDotNet.sh' 3.1"
Adding Microsoft repository key and feed
--2020-07-09 09:13:26--  https://packages.microsoft.com/config/ubuntu/14.04/packages-microsoft-prod.deb
Resolving packages.microsoft.com (packages.microsoft.com)... 23.99.120.248
Connecting to packages.microsoft.com (packages.microsoft.com)|23.99.120.248|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2446 (2.4K) [application/octet-stream]
Saving to: ‘/tmp/packages-microsoft-prod.deb’

100%[================================================>] 2,446       --.-K/s   in 0s

2020-07-09 09:13:26 (99.3 MB/s) - ‘/tmp/packages-microsoft-prod.deb’ saved [2446/2446]

[sudo] password for testusr:

...[생략]...

경우에 따라 다음과 같이 설치 실패가 발생할 수 있습니다.

...[생략]...

Hit http://archive.ubuntu.com trusty/universe Translation-en
Hit http://archive.ubuntu.com trusty/universe Translation-ko
Ign http://archive.ubuntu.com trusty/main Translation-en_US
Ign http://archive.ubuntu.com trusty/multiverse Translation-en_US
Ign http://archive.ubuntu.com trusty/multiverse Translation-ko
Ign http://archive.ubuntu.com trusty/restricted Translation-en_US
Ign http://archive.ubuntu.com trusty/universe Translation-en_US
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package aspnetcore-runtime-3.1
E: Couldn't find any package by regex 'aspnetcore-runtime-3.1'
Press any key to continue . . .

실패 원인을 밝히려면 자신의 WSL 2 리눅스 배포본을 확인할 필요가 있습니다. 가령 제 경우에는,

C:\Windows\System32> wsl
testusr@TESTPC:/mnt/c/Windows/System32$ cat /etc/os-release
NAME="Ubuntu"
VERSION="14.04.6 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.6 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
root@TESTPC:~#

기본 WSL 2 환경으로 14.04 버전의 우분투 배포본이 지정되어 있어 .NET Core 3.1이 설치될 수 없었습니다. 이를 해결하려면 "wsl" 명령어가 실행하는 기본 리눅스 배포본을 .NET Core 3.1이 설치될 수 있는 환경으로 바꿔야 합니다. 따라서, 새롭게 Windows Store에서 - 예를 들어 18.04 버전의 우분투를 설치해,

Ubuntu 18.04 LTS
; https://www.microsoft.com/en-us/p/ubuntu-1804-lts/9n9tngvndl3q

이것을 비주얼 스튜디오가 사용하도록 만들면 됩니다.




참고로, 비주얼 스튜디오가 "WSL 2" 옵션으로 프로그램을 실행하는 경우 기본적으로 선택되는 리눅스 배포본은 wsl.exe를 이용해 바꿀 수 있습니다. 이를 위해 우선 현재 설치된 배포본 목록을 다음과 같이 확인하면,

C:\Windows\System32> wsl --list
Windows Subsystem for Linux Distributions:
Legacy (Default)
Ubuntu
Ubuntu-18.04
docker-desktop-data
docker-desktop

위에서는 "Legacy" 버전이 "(Default)"로 지정되어 있는 것입니다. 만약 위의 목록에서 "Ubuntu-18.04" 배포본을 wsl.exe의 기본 실행 환경으로 바꾸고 싶다면 다음과 같이 명령을 내리면 됩니다.

C:\Windows\System32> wsl --set-default Ubuntu-18.04

원한다면, 디스크 공간 절약을 위해 기존 Legacy 배포본을 "--unregister" 옵션을 이용해 삭제하는 것도 가능합니다.

C:\Windows\System32> wsl --unregister Legacy
Unregistering...

C:\Windows\System32> wsl --list
Windows Subsystem for Linux Distributions:
Ubuntu-18.04 (Default)
docker-desktop-data
docker-desktop

wsl.exe에 대한 좀 더 자세한 사항은 다음의 글을 참고하시고.

Windows Subsystem for Linux Installation Guide for Windows 10
; https://learn.microsoft.com/ko-kr/windows/wsl/install-win10




첫 번째 디버깅 환경 구성을 마치고, 경우에 따라 추가로 다음과 같은 식의 오류가 발생할 수 있습니다.

Try running your application again once the script in the command window has completed. You may need to interact with the script.

OK 버튼을 누르면, 첫 번째 환경 구성 단계에서 못했던 디버깅 환경을 마저 구성하는데,

C:\WINDOWS\System32\bash.exe -c "'/mnt/c/USERS/TESTUSR/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/16.0_898C74B1/EXTENSIONS/5YKPGVGM.BZA/Scripts/UpdateDebuggerInteractive.sh'"
Info: Previous installation at '/home/testusr/vsdbg' not found
Info: Using vsdbg version '16.6.20415.1'
Info: Creating install directory
Using arguments
    Version                    : 'latest'
    Location                   : '/home/testusr/vsdbg'
    SkipDownloads              : 'false'
    LaunchVsDbgAfter           : 'false'
    RemoveExistingOnUpgrade    : 'false'
Info: Using Runtime ID 'linux-x64'
Downloading https://vsdebugger.azureedge.net/vsdbg-16-6-20415-1/vsdbg-linux-x64.tar.gz

위의 과정이 끝나면 이후 정상적으로 동작합니다.




아직 Preview 버전이라서 그런지, .NET Core Console 응용 프로그램은 "WSL 2" 환경에서 잘 실행이 되지만, ASP.NET Core 웹 응용 프로그램의 경우에는 초기화 과정 중 "The thread ... has exited with code" 출력 이후 포트가 닫히게 됩니다.

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
Microsoft.Hosting.Lifetime: Information: Now listening on: http://localhost:5000
Microsoft.Hosting.Lifetime: Information: Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
Microsoft.Hosting.Lifetime: Information: Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /mnt/e/testapp/WebApplication1/WebApplication1
Microsoft.Hosting.Lifetime: Information: Content root path: /mnt/e/testapp/WebApplication1/WebApplication1
The thread 0xe52 has exited with code 0 (0x0).

정식 버전에서는 아마 바뀌겠지요. ^^ 그리고 또 한가지, 현재 Debug 모드로 시작(F5)해야 정상적으로 실행이 되고, 디버그 없이 시작(Ctrl + F5)하는 경우 이런 오류가 발생하며 실행이 안 됩니다.

Item has already been added. Key in dictionary: 'NUGET_PACKAGES'  Key being added: 'NUGET_PACKAGES'

아마 이것 역시 정식 버전에서는 바뀔 것이고. ^^




마지막으로, 다음과 같은 오류가 발생한다면?

The project doesn't know how to run the profile WSL 2.

".NET Core Debugging with WSL 2 - Preview" 도구가 설치되지 않은 비주얼 스튜디오에서 (다른 컴퓨터에서 지정한 "WSL 2" 설정으로 인해) "WSL 2" 모드로 실행하려고 한 경우입니다.




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







[최초 등록일: ]
[최종 수정일: 3/9/2024]

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

비밀번호

댓글 작성자
 



2020-07-10 01시07분
[이성환] wsl --list -v 에 -v 옵션은 Windows 10 19041 이상에서만 사용할 수 있군요. 왜 안 되나 찾다가 윈도 업데이트 하는데 한시간 걸렸... 쿨럭....
[guest]
2020-07-10 01시10분
그런데, 어차피 이 글의 실습을 위해 "WSL 2" 기능을 사용하려면 윈도우 10 버전 2004가 필요합니다.
정성태
2020-07-10 01시54분
[이성환] 아... 넵. 그렇군요. 일단 터미널이랑 우분투 20.04 설치가 가능하길래 인지 못하고 진행했습니다. -ㅁ-;; 그러다 막혀서 헤맸죠...
그리고 중간에 커널 업데이트를 해야하는데, 저는 msi 파일 실행하니까, "this update is applied to machines with the Windows System for linux" 라는 팝업이 뜨고 설치가 안 되더라구요.
저는 https://github.com/microsoft/WSL/issues/5014#issuecomment-605243281 요 링크로 해결이 됐습니다. 혹시 막히는 분들을 위해... >ㅂ<
[guest]
2020-07-28 04시19분
Official Support for Remote Debugging a .NET Core Linux app in WSL2 from Visual Studio on Windows
; https://www.hanselman.com/blog/official-support-for-remote-debugging-a-net-core-linux-app-in-wsl2-from-visual-studio-on-windows
정성태
2020-10-13 09시02분
WSL 리눅스 인스턴스를 외부에서 업데이트하는 방법을 소개합니다.

Keeping your WSL Linux instances up to date automatically within Windows 10
; https://www.hanselman.com/blog/keeping-your-wsl-linux-instances-up-to-date-automatically-within-windows-10

예) wsl -d Ubuntu-20.04 -u root -e apt update
    wsl -d Ubuntu-20.04 -u root -e apt upgrade -y
정성태

1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13356정성태5/15/20233894DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233830.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234089.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233698.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234207VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233477오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233783.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233687.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234077.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233905오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235282.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236489.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234361디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234272.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234005닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234079오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234742닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234261닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234765Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234571.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234673.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234308Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233750Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233853Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233884오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233526Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...