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

(시리즈 글이 5개 있습니다.)
Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
; https://www.sysnet.pe.kr/2/0/13540

개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
; https://www.sysnet.pe.kr/2/0/13548

개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
; https://www.sysnet.pe.kr/2/0/13549

닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
; https://www.sysnet.pe.kr/2/0/13574

닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법
; https://www.sysnet.pe.kr/2/0/13616




"Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)

예를 들기 위해, 비주얼 스튜디오에서 ASP.NET Core 웹 프로젝트를 "Enable Docker" 옵션을 체크하고 만듭니다. (또는, 해당 옵션 없이 만든 후 "Add" / "Docker Support..." 메뉴를 선택해도 됩니다.)

이제 F5 키를 눌러 실행하면, 비주얼 스튜디오의 "Containers" 뷰(단축키: Ctrl+K, Ctrl+O)에서 다음과 같은 출력 내용을 볼 수 있습니다.

warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
      Storing keys in a directory '/home/app/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed. For more information go to https://aka.ms/aspnet/dataprotectionwarning
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {85a48ab0-5ffe-4904-ab57-f396acf433fd} may be persisted to storage in unencrypted form.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://[::]:8080
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /app

"[::]"은 IPAddress.IPv6Any 주소를 의미하는데요, IPv4도 같이 매핑이 됩니다.

$ netstat -ant | grep LISTEN
tcp6       0      0 :::8080                 :::*                    LISTEN

$ cat /proc/sys/net/ipv6/bindv6only
0

하지만 (기본적으로는) 정작 컨테이너 환경 내에서 IPv4 형식만 지원하기 때문에,

$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.0.2  netmask 255.255.0.0  broadcast 172.17.255.255
        ether 02:42:ac:11:00:02  txqueuelen 0  (Ethernet)
        RX packets 143  bytes 15531 (15.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 122  bytes 338731 (330.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 60  bytes 17200 (16.7 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 60  bytes 17200 (16.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

127.0.0.1, 172.17.0.2와 같은 IPv4 주소를 지정한 요청만 받아들일 수 있습니다.

$ curl http://172.17.0.2:8080
...[OK]...

$ curl http://127.0.0.1:8080
...[OK]...

$ curl http://[::1]:8080
curl: (7) Failed to connect to ::1 port 8080 after 0 ms: Couldn't connect to server

물론, 컨테이너 환경 내에서 저런 제약이 있는 것이고, 해당 포트를 외부로 매핑한 경우에는, 예를 들어 "-p 16000:8080"으로 매핑시켜 노출했다면 외부에서는 IPv6, IPv4에 상관 없이 접근할 수 있습니다.

// Docker Desktop을 호스팅하는 윈도우 환경으로 가정

c:\temp> curl [::1]:16000
...[OK]...

// 윈도우 측의 IPv6 주소가 "fe80::cef1:2a62:aee0:1ca9"인 경우,
c:\temp> curl [fe80::cef1:2a62:aee0:1ca9]:16000
...[OK]...

c:\temp> curl localhost:8080
...[OK]...

하지만, 외부에서 IPv6로 접속했다고 해서 내부의 IPv6 [::] 주소로 Accept가 된 것은 아닙니다. 예를 들어, telnet으로 간단하게 TCP 커넥션을 열어두도록 접속하는 경우,

c:\temp> telnet [::1] 16000

컨테이너 내부에서 보면, IPv4 0.0.0.0 소켓에서 Accept 처리했음을 확인할 수 있습니다.

$ netstat -ano
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       Timer
tcp6       0      0 :::8080                 :::*                    LISTEN      off (0.00/0/0)
tcp6       0      0 172.17.0.2:8080         172.17.0.1:37966        ESTABLISHED off (0.00/0/0)
...[생략]...




ASP.NET Core 프로젝트를 .NET 8 런타임으로 생성하면 (기본값이 5000이 아닌) 8080 포트로 서비스하는 이유는 launchSettings.json에 ASPNETCORE_HTTP_PORTS 옵션이 8080으로 설정돼 있기 때문입니다.

"Docker": {
    "commandName": "Docker",
    "launchBrowser": true,
    "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
    "environmentVariables": {
        "ASPNETCORE_HTTP_PORTS": "8080"
    },
    "publishAllPorts": true
}

또한, 그 8080으로 컨테이너 외부에서 접근할 수 있도록 자동으로 랜덤 포트를 하나 매핑해 주는데요, 그것은 위의 옵션에서 설정한 "publishAllPorts" 옵션 때문입니다. 이 옵션이 true면, dockerfile에 "EXPOSE" 설정이 된 모든 포트를 매핑시켜줍니다.

가령, 기본으로는 8080만 있을 텐데요, 여기에 임의로 다른 포트를 하나 더하면,

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app

EXPOSE 8080
EXPOSE 5000

...[생략]...

이것 역시 랜덤 포트로 매핑이 됩니다. 엄밀히 말해서 "publishAllPorts" 옵션이 그렇게 해주는 것은 아니고, 그 옵션을 읽어낸 비주얼 스튜디오가 "docker run" 시에 "-P" 설정을 추가하기 때문입니다.

만약, "랜덤 포트"를 사용하고 싶지 않다면 csproj에 DockerfileRunArguments 옵션을 줘 고정할 수 있는데요, 가령 아래와 같은 설정을 하게 되면,

<DockerfileRunArguments>-p 16000:8080</DockerfileRunArguments>

이제 비주얼 스튜디오는 ("publishAllPorts"이 있는 경우 "-P" 옵션도 주겠지만) 명시적으로 "-p 16000:8080" 설정을 "docker run" 시에 추가함으로써 우리가 원하는 포트를 사용할 수 있게 해줍니다.




대개의 경우 기본 설정된 "ASPNETCORE_HTTP_PORTS": "8080" 옵션으로 인해 [::] Any 바인딩을 그대로 사용하겠지만, 때로는 Reverse Proxy 등을 사용한다면 보안상 localhost로만 매핑하고 싶은 상황도 발생할 것입니다.

Host ASP.NET Core on Linux with Nginx
; https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx

이를 위해서는 ASPNETCORE_URLS 옵션 등을 통해 바인딩 정보를 바꿀 수 있습니다.

"Docker": {
    "commandName": "Docker",
    "launchBrowser": true,
    "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
    "environmentVariables": {
        // "ASPNETCORE_HTTP_PORTS": "8080"
        "ASPNETCORE_URLS": "http://localhost:8080"
    },
    "publishAllPorts": true
}

그럼, F5 실행 시 컨테이너 로그에는 이렇게 바인딩 정보가 바뀌어 출력됩니다.

warn: Microsoft.AspNetCore.Hosting.Diagnostics[15]
      Overriding HTTP_PORTS '8080' and HTTPS_PORTS ''. Binding to values defined by URLS instead 'http://localhost:8080'.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:8080

그리고 이제부터는, 설령 외부에 "-p 16000:8080" 설정으로 포트 매핑을 시켰다고 해도 윈도우 호스트 측에서 컨테이너 내부의 웹 서비스로 접근하는 것이 불가능합니다. 그렇기 때문에 비주얼 스튜디오에서 자동으로 실행한 웹 브라우저 화면에는 "http://localhost:16000/"로 방문은 하지만 다음과 같은 오류 화면만 보게 됩니다.

This page isn't working right now
localhost didn't send any data.
ERR_EMPTY_RESPONSE

또는, curl을 이용해 컨테이너 내부와 외부에서 간단하게 테스트할 수 있습니다.

// Container 내부에서 실행

$ netstat -ant | grep LISTEN
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN  

$ curl http://127.0.0.1:8080
...[OK]

// Container 외부에서 실행

c:\temp> curl http://127.0.0.1:16000
curl: (52) Empty reply from server

c:\temp> curl http://[::1]:8080
curl: (7) Failed to connect to ::1 port 8080 after 0 ms: Couldn't connect to server

위와 같은 동작의 이유는 간단합니다. "localhost" 바인딩은 "0.0.0.0"이 아닌 "127.0.0.1"에 대한 요청만 허용하기 때문에 컨테이너 외부에서 들어오는 요청에는 반응할 수 없습니다.

그나저나, 위의 출력에서 "Container 외부에서 실행"하는 경우 curl의 출력이 "Empty reply from server"인 것이 좀 이상하지 않나요? ^^ 원래는 "Couldn't connect to server"라고 나와야 하는데요, 분량상 이에 대해서는 다른 글에서 자세하게 더 다뤄보겠습니다.




중요한 것은 아니지만, 여기서 하나 더 테스트를 해보겠습니다. ^^ 이를 위해 "appsettings.json", 만약 디버깅 중이라면 "appsettings.Development.json" 파일의 내용 중 "Microsoft.AspNetCore" 설정을 "Warning"에서 "Information"으로 바꿔 보겠습니다.

{
  "DetailedErrors": true,
  "Logging": {
    "LogLevel": {
      "Default": "Information",
        // "Microsoft.AspNetCore": "Warning"
        "Microsoft.AspNetCore": "Information"
    }
  }
}

이 상태에서 다시 F5 디버깅을 시도하면 이제 컨테이너 출력에는 다음과 같은 내용이 포함됩니다.

// ...[생략]...
info: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to bind to http://localhost:8080 on the IPv6 loopback interface: 'Cannot assign requested address'.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:8080
// ...[생략]...

지난 글에서 다룬 바로 그 내용이,

리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
; https://www.sysnet.pe.kr/2/0/13540

ASP.NET Core 웹 프로젝트의 경우에도 그대로 발생하는 것입니다.




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







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

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

비밀번호

댓글 작성자
 




... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13198정성태12/18/20224815.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224609.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/20224816.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
13195정성태12/15/20225300개발 환경 구성: 655. docker - bridge 네트워크 모드에서 컨테이너 간 통신 시 --link 옵션 권장 이유
13194정성태12/14/20225411오류 유형: 833. warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock파일 다운로드1
13193정성태12/14/20225520오류 유형: 832. error C7681: two-phase name lookup is not supported for C++/CLI or C++/CX; use /Zc:twoPhase-
13192정성태12/13/20225571Linux: 55. 리눅스 - bash shell에서 실수 연산
13191정성태12/11/20226479.NET Framework: 2077. C# - 직접 만들어 보는 SynchronizationContext파일 다운로드1
13190정성태12/9/20226964.NET Framework: 2076. C# - SynchronizationContext 기본 사용법파일 다운로드1
13189정성태12/9/20227835오류 유형: 831. Visual Studio - Windows Forms 디자이너의 도구 상자에 컨트롤이 보이지 않는 문제
13188정성태12/9/20226421.NET Framework: 2075. C# - 직접 만들어 보는 TaskScheduler 실습 (SingleThreadTaskScheduler)파일 다운로드1
13187정성태12/8/20226370개발 환경 구성: 654. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법 (2)
13186정성태12/6/20224906오류 유형: 831. The framework 'Microsoft.AspNetCore.App', version '...' was not found.
13185정성태12/6/20225876개발 환경 구성: 653. Windows 환경에서의 Hello World x64 어셈블리 예제 (NASM 버전)
13184정성태12/5/20225059개발 환경 구성: 652. ml64.exe와 link.exe x64 실행 환경 구성
13183정성태12/4/20225077오류 유형: 830. MASM + CRT 함수를 사용하는 경우 발생하는 컴파일 오류 정리
13182정성태12/4/20225804Windows: 217. Windows 환경에서의 Hello World x64 어셈블리 예제 (MASM 버전)
13181정성태12/3/20225197Linux: 54. 리눅스/WSL - hello world 어셈블리 코드 x86/x64 (nasm)
13180정성태12/2/20225274.NET Framework: 2074. C# - 스택 메모리에 대한 여유 공간 확인하는 방법파일 다운로드1
13179정성태12/2/20224612Windows: 216. Windows 11 - 22H2 업데이트 이후 Terminal 대신 cmd 창이 뜨는 경우
13178정성태12/1/20225169Windows: 215. Win32 API 금지된 함수 - IsBadXxxPtr 유의 함수들이 안전하지 않은 이유파일 다운로드1
13177정성태11/30/20225854오류 유형: 829. uwsgi 설치 시 fatal error: Python.h: No such file or directory
13176정성태11/29/20224738오류 유형: 828. gunicorn - ModuleNotFoundError: No module named 'flask'
13175정성태11/29/20226566오류 유형: 827. Python - ImportError: cannot import name 'html5lib' from 'pip._vendor'
13174정성태11/28/20224979.NET Framework: 2073. C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력파일 다운로드1
13173정성태11/27/20225756.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...