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)
13528정성태1/14/20242033Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241960오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242051닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242021오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242066오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241889오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242030닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242110닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241858오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241938닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242174닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242017스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242104닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242376닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242065개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242006닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20241979개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20241996닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241937닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241966오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242016오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242701닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232191닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232706닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232322닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232191Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...