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

비밀번호

댓글 작성자
 




1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13545정성태1/30/20242154닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20242183오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20242216Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20242240오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20242332VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242476Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242437개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242548닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242661닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242688닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242590닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242361닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242551닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242461닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242436닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242293닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242188닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242342Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242263오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242339닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242295오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242372오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242179오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242306닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242385닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242178오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...