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)
13249정성태2/7/20234946오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234052오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20234965VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234095개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234642.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234001VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234862디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234306디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233831디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20233988디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233631디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235647.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235336.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20234974개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234523개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235563개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20236912오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234710스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233623오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234035개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20234985.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235121.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234832개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234516.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233759개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234119Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...