[Kubernetes](EN) kubectl port-forward usage and example

kubectl port-forward usage and example


Environment and Prerequisite

  • Kubernetes
  • kubectl


Background

  • While using Kubernetes, I frequently use port forwarding but I often forget how to use it so I post it remember it.


kubectl port-forward

Official Document

  • There are good examples on official document.
  • Not only Pod but also Deployment and Service can be used.
  • You can use --address option to specify the IP address to listen on. It is separated by , and default values are localhost and 127.0.0.1.

Usage

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

Example

 # 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


Usage Examples

Port forward to Pod

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

Port forward to Deployment

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

Port forward to Service

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

Set listen IP address

  • Listen on all IP addresses
kubectl port-forward --address 0.0.0.0 pod/[pod name] [local port]:[port]
  • Listen on local and specific IP address
  • In the example below, it is assumed that the OS instance has the address 10.19.21.23. This is like specifying the IP address for port connection rather than a concept like a whitelist that controls external access.
kubectl port-forward --address localhost,10.19.21.23 pod/[pod name] [local port]:[port]


Reference