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)
13584정성태3/26/20241458개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241491Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241580Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241759개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241292닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241499오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241644닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241910닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241579닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241699닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241570닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241577닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241662닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241637닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241645닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241551닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241618닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241625오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241637오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241624닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241909Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241948디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241959오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20242034닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20242051디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242936오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...