내용으로 건너뛰기

EKS 클러스터에서 kubectl exec/attach/port-forward 수행 시 "Connection Refused" 오류가 반환될 경우 문제를 해결하는 방법은 무엇인가요?

5분 분량
콘텐츠 수준: 중급
2

EKS 클러스터에서 kubectl exec, kubectl attach, kubectl port-forward 명령어 수행 시 NodePort 충돌로 인해 반환되는 connection refused 오류를 해결합니다.

문제 상황

아래 예시 EKS 클러스터에서는 test라는 이름의 Kubernetes Service가 생성되었고, NodePort 32413이 할당되어 있습니다. 해당 EKS 클러스터에 대해 kubectl exec, kubectl attach, kubectl port-forward 명령을 수행하면 connection refused 오류가 발생하며 작업이 실패합니다. 해당 오류가 발생한 주소는 127.0.0.1:32413로 NodePort와 동일합니다.

kubectl get service -o wide
# 출력
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE     SELECTOR
kubernetes   ClusterIP   172.20.0.1      <none>        443/TCP        4h51m   <none>
test         NodePort    172.20.31.178   <none>        80:32413/TCP   10m     app=test

kubectl exec -it nginx -- sh
# 출력
error: Internal error occurred: error sending request: Post "http://127.0.0.1:32413/exec/LcTQpAQI": dial tcp 127.0.0.1:32413: connect: connection refused

kubectl attach -it nginx
# 출력
error: Unable to use a TTY - container nginx did not allocate one
All commands and output from this session will be recorded in container logs, including credentials and sensitive information passed through the command prompt.
If you don't see a command prompt, try pressing enter.
error: Internal error occurred: error sending request: Post "http://127.0.0.1:32413/attach/rKLmT4oT": dial tcp 127.0.0.1:32413: connect: connection refused

kubectl port-forward nginx 8080:80
# 출력
error: error upgrading connection: unable to upgrade connection: error dialing backend: dial tcp 127.0.0.1:32413: connect: connection refused

배경

kubectl exec, kubectl attach, kubectl port-forward 요청은 대상 파드가 스케줄링된 노드에서 실행 중인 containerd Streaming Server로 라우팅됩니다. 이 서버는 파드 컨테이너의 실시간 stdin/stdout/stderr 데이터를 스트리밍하며, 각 노드의 127.0.0.1에서 리스닝합니다.

containerd Streaming Server가 사용하는 포트는 containerd 설정 파일(/etc/containerd/config.toml)에 정의된 stream_server_port 값에 따라 결정됩니다. 이 값이 0이거나 설정되어 있지 않은 경우, net.ipv4.ip_local_port_range 커널 파라미터로 정의된 범위 내에서 임의의 포트가 할당됩니다.

한편, EKS 최적화 AMI에서 net.ipv4.ip_local_port_range의 기본 범위는 32768–60999이며, 이는 각 EKS 노드의 Streaming Server가 기본적으로 127.0.0.1:32768부터 127.0.0.1:60999 사이의 포트를 할당받음을 의미합니다. Kubernetes Service NodePort의 기본 범위는 30000–32767이므로, 일반적으로 Streaming Server 포트와 Service NodePort는 중복되지 않습니다.

sysctl net.ipv4.ip_local_port_range
# 출력
net.ipv4.ip_local_port_range = 32768    60999

sudo ss -tlnp | grep containerd
# 출력
LISTEN 0      4096        127.0.0.1:39119      0.0.0.0:*    users:(("containerd",pid=2116,fd=4))

하지만 노드의 net.ipv4.ip_local_port_range 커널 파라미터가 변경되어 그 범위가 Service NodePort 범위의 전체 또는 일부와 겹치게 되면, 해당 노드의 containerd Streaming Server가 Service NodePort와 동일한 포트를 사용하게 될 수 있습니다. Streaming Server의 포트는 containerd가 재시작될 때마다 임의로 재할당되므로, Streaming Server가 Service NodePort 범위 내의 포트를 할당받게 될 가능성이 항상 존재합니다.

sysctl net.ipv4.ip_local_port_range
# 출력
net.ipv4.ip_local_port_range = 11000    65535

sudo ss -tlnp | grep containerd
# 출력
LISTEN 0      4096        127.0.0.1:32413      0.0.0.0:*    users:(("containerd",pid=45972,fd=41))

Streaming Server와 Service NodePort에 동일한 포트가 할당되면, kubectl exec, kubectl attach, kubectl port-forward 요청이 Streaming Server가 아닌 Kubernetes Service로 라우팅됩니다. 기본적으로 Kubernetes Service는 스트리밍 API 경로(/exec, /attach 등)를 처리하는 로직이 존재하지 않기 때문에 connection refused 오류가 반환됩니다. 만약 Service의 레이블 셀렉터가 특정 파드와 일치하는 경우에는 해당 파드가 대신 스트리밍 API 요청을 처리하게 되는데, 파드 역시 일반적으로 이러한 경로에 대한 핸들러를 구현하고 있지 않으므로 404 Not Found 오류가 반환될 수 있습니다.

aws eks update-kubeconfig --name EKS_CLUSTER_NAME

cat << EOF | kubectl apply -f -
apiVersion: v1
kind: Service
metadata:
  name: test
spec:
  type: NodePort
  selector:
    app: test
  ports:
    - port: 80
      targetPort: 80
      nodePort: 32413 # containerd streaming server와 동일 포트 사용
---
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - containerPort: 80
EOF

kubectl exec -it nginx -- sh
# 출력
error: Internal error occurred: error sending request: Post "http://127.0.0.1:32413/exec/LcTQpAQI": dial tcp 127.0.0.1:32413: connect: connection refused

진단

파드가 실행 중인 노드에서 net.ipv4.ip_local_port_range 커널 파라미터의 범위가 Kubernetes Service NodePort 범위(기본값: 30000–32767)와 겹치는지 확인합니다. 두 범위에 모두 포함되는 포트는 containerd Streaming Server와 Kubernetes Service NodePort에 동시에 할당될 수 있으며, 이로 인해 connection refused 또는 404 Not Found와 같은 오류가 발생할 수 있습니다. 다음 두 가지 방법 중 하나로 커널 파라미터를 확인할 수 있습니다.

a. 노드 인스턴스의 사용자 데이터(user data)에 net.ipv4.ip_local_port_range 범위를 변경하는 sysctl -w(임시 적용) 또는 sysctl -p/sysctl --system(영구 적용) 명령이 포함되어 있는지 확인합니다. 다음은 AmazonLinux2023(AL2023) 노드 사용자 데이터의 예시입니다.

# AmazonLinux2023 노드 인스턴스 사용자 데이터 예시

MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="//"

...

--//
Content-Type: text/x-shellscript; charset="us-ascii"

#!/bin/bash

...

echo "net.ipv4.ip_local_port_range = 11000 65535" >> /etc/sysctl.conf
sysctl -p

...

--//--

b. SSH 또는 Session Manager를 통해 노드 인스턴스에 접속한 뒤 다음 명령을 실행하여 시스템에 현재 적용되어 있는 net.ipv4.ip_local_port_range 범위를 확인합니다.

sysctl net.ipv4.ip_local_port_range

해결 방법

containerd Streaming Server 포트를 명시적으로 고정

containerd 설정 파일(/etc/containerd/config.toml)에서 stream_server_port를 0이 아닌 고정된 값으로 설정한 뒤, systemctl restart containerd 명령으로 containerd를 재시작합니다. 이렇게 설정하면 Streaming Server는 stream_server_port에 지정된 포트만 사용하게 됩니다. 다음은 containerd Streaming Server를 127.0.0.1:33333으로 고정하는 예시입니다.

# /etc/containerd/config.toml
...
[plugins."io.containerd.grpc.v1.cri"]
disable_tcp_service = true
stream_server_address = "127.0.0.1"
stream_server_port = "33333"
...

net.ipv4.ip_local_port_range와 NodePort 범위를 분리하여 유지

/etc/sysctl.conf를 수정하여 net.ipv4.ip_local_port_range 값이 Kubernetes Service NodePort 범위(30000–32767)와 전체 또는 일부 겹치지 않도록 설정한 뒤, sysctl -p / sysctl --system 명령으로 변경 사항을 영구적으로 적용합니다. 다음은 임시 포트(ephemeral port) 범위(32768–65535)를 NodePort 범위(30000–32767)와 분리한 예시입니다.

# /etc/sysctl.conf
...
net.ipv4.ip_local_port_range = 32768 65535
...
AWS
전문가

게시됨 3달 전208회 조회