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
정성태

... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12856정성태11/23/20218900.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216246개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217803개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216168오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217559스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218733오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217869스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218820스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218664스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218418스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218246.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216251오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216698스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202125053오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218521스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218621.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219672.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219325.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218231VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217840Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20219078.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217479오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216920VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217781VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216318VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218579오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...