[Kubernetes] kubectl port-forward 사용 방법과 예제

kubectl port-forward 사용 방법과 예제


환경

  • Kubernetes
  • kubectl


배경

  • Kubernetes 사용시 포트 포워딩을 자주 사용하는데 사용법을 까먹어서 기억할 목적으로 정리.


kubectl port-forward

공식 문서

  • 공식 문서에 보면 예시가 잘 나와있다.
  • Pod뿐만 아니라 Deployment와 Service에도 사용할 수 있었다.
  • --address 옵션을 사용하면 수신할 IP 주소를 지정할 수 있다. ,로 구분되며 기본값은 localhost127.0.0.1다.

사용 방법

kubectl port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]

예시

 # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
 kubectl port-forward pod/mypod 5000 6000
  
 # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the deployment
 kubectl port-forward deployment/mydeployment 5000 6000
 
 # Listen on port 8443 locally, forwarding to the targetPort of the service's port named "https" in a pod selected by the service
 kubectl port-forward service/myservice 8443:https
 
 # Listen on port 8888 locally, forwarding to 5000 in the pod
 kubectl port-forward pod/mypod 8888:5000
 
 # Listen on port 8888 on all addresses, forwarding to 5000 in the pod
 kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000
 
 # Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
 kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000
 
 # Listen on a random port locally, forwarding to 5000 in the pod
 kubectl port-forward pod/mypod :5000


예시별 사용 방법

Pod에 포트 포워딩

kubectl port-forward pod/[pod name] [local port]:[pod port]

Deployment에 포트 포워딩

kubectl port-forward deployment/[deployment name] [local port]:[pod port]

Service에 포트 포워딩

kubectl port-forward service/[service name] [local port]:[service port]

수신 IP 주소 지정

  • 모든 IP에 대해 수신해서 포트 포워딩
kubectl port-forward --address 0.0.0.0 pod/[pod name] [local port]:[port]
  • 로컬 및 특정 IP에 대해 수신해서 포트 포워딩
  • 아래의 경우 명령어를 실행하는 OS 인스턴스가 10.19.21.23 주소를 가지고 있다고 가정한 경우로 외부에서 접근을 제어하는 Whitelist 같은 개념이 아니라 포트를 연결할 IP 주소를 명시하는 경우로 보면 된다.
kubectl port-forward --address localhost,10.19.21.23 pod/[pod name] [local port]:[port]


참고자료