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)
13177정성태11/30/20225875오류 유형: 829. uwsgi 설치 시 fatal error: Python.h: No such file or directory
13176정성태11/29/20224745오류 유형: 828. gunicorn - ModuleNotFoundError: No module named 'flask'
13175정성태11/29/20226610오류 유형: 827. Python - ImportError: cannot import name 'html5lib' from 'pip._vendor'
13174정성태11/28/20225007.NET Framework: 2073. C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력파일 다운로드1
13173정성태11/27/20225791.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225482.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20225160Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225399Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20226006Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20225337제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20225379.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20225107개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224908개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225908개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225814개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226873.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20226191.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20226073.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20229374.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225474오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20226130.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20227089.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226558디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20226059.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20227363.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225957.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
... 16  17  18  [19]  20  21  22  23  24  25  26  27  28  29  30  ...