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

(시리즈 글이 4개 있습니다.)
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




"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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13609정성태4/27/202457닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/2024423닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024420닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024450닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024698닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024729오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024884닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024943닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024971닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024981닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024938닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024980닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024975닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241080닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241070닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241085닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241091닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241227C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241203닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241084Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241159닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241278닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241362오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241538Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241499Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...