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

... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...
NoWriterDateCnt.TitleFile(s)
12871정성태12/12/20217458오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/20216064개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/20218269개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
12868정성태12/7/20216838오류 유형: 770. twine 업로드 시 "HTTPError: 400 Bad Request ..." 오류 [1]
12867정성태12/7/20216546개발 환경 구성: 612. 파이썬 - PyPI 패키지 만들기 (3) entry_points 옵션
12866정성태12/7/202113917오류 유형: 769. "docker build ..." 시 "failed to solve with frontend dockerfile.v0: failed to read dockerfile ..." 오류
12865정성태12/6/20216614개발 환경 구성: 611. 파이썬 - PyPI 패키지 만들기 (2) long_description, cmdclass 옵션
12864정성태12/6/20215088Linux: 46. WSL 환경에서 find 명령을 사용해 파일을 찾는 방법
12863정성태12/4/20216987개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기
12862정성태12/3/20215727오류 유형: 768. Golang - 빌드 시 "cmd/go: unsupported GOOS/GOARCH pair linux /amd64" 오류
12861정성태12/3/20217950개발 환경 구성: 609. 파이썬 - "Windows embeddable package"로 개발 환경 구성하는 방법
12860정성태12/1/20216054오류 유형: 767. SQL Server - 127.0.0.1로 접속하는 경우 "Access is denied"가 발생한다면?
12859정성태12/1/202112206개발 환경 구성: 608. Hyper-V 가상 머신에 Console 모드로 로그인하는 방법
12858정성태11/30/20219457개발 환경 구성: 607. 로컬의 USB 장치를 원격 머신에 제공하는 방법 - usbip-win
12857정성태11/24/20216946개발 환경 구성: 606. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법
12856정성태11/23/20218729.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216124개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217670개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216059오류 유형: 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/20217369스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218516오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217688스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218645스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218485스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218253스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218096.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...