kubectl port-forward to another endpoint
Asked Answered
R

3

16

Is there a corresponding command with kubectl to:

ssh -L8888:rds.aws.com:5432 example.com

kubectl has port-forward you can also specify --address but that strictly requires an IP address.

Rolandorolandson answered 16/4, 2020 at 22:53 Comment(1)
"kubectl port-forward" is intended to forward local ports ( optionally only from "--address" local IP address ) to a pod port in k8s cluster. It doesn't forward ports to any destination, just inside k8s cluster.Lipophilic
O
17

The older answer is valid. Still, a workaround would be to use something like https://hub.docker.com/r/marcnuri/port-forward

kubectl run --env REMOTE_HOST=your.service.com --env REMOTE_PORT=8080 --env LOCAL_PORT=8080 --port 8080 --image marcnuri/port-forward test-port-forward

Run it on the cluster and then port forward to it.

kubectl port-forward test-port-forward 8080:8080

Octillion answered 6/1, 2021 at 15:6 Comment(1)
But the kubectl has to run into the remote host or local?Exploitation
S
7

Short answer, No.

In OpenSSH, local port forwarding is configured using the -L option:

   ssh -L 80:intra.example.com:80 gw.example.com

This example opens a connection to the gw.example.com jump server, and forwards any connection to port 80 on the local machine to port 80 on intra.example.com.

By default, anyone (even on different machines) can connect to the specified port on the SSH client machine. However, this can be restricted to programs on the same host by supplying a bind address:

   ssh -L 127.0.0.1:80:intra.example.com:80 gw.example.com

You can read the docs here.

The port-forward in Kubernetes works only within the cluster, you can forward traffic that will hit specified port to Deployment or Service or a Pod

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

--address flag is to specify what to listen on 0.0.0.0 means everything localhost is as name and you can set an IP on which it can be listening on. Documentation is available here, you can also read Use Port Forwarding to Access Applications in a Cluster.

Strata answered 17/4, 2020 at 12:31 Comment(0)
S
6

One workaround you can use if you have an SSH server somewhere on the Internet is to SSH to your server from your pod, port-forwarding in reverse:

# Suppose a web console is being served at 
# http://my-service-8f6717ab-e.default:8888/
# inside your cluster:

kubectl exec -it my-job-f523b248-7htj6 -- ssh -R8888:my-service-8f6717ab-e.default:8888 [email protected]

Then you can connect to the service inside Kubernetes from outside of it. If the SSH server is not local to you, you can SSH to it from your local machine with a normal port forward:

me@my-macbook-pro:$ ssh -L8888:localhost:8888 [email protected]

Then point your browser to http://localhost:8888/

Sonata answered 3/8, 2021 at 5:11 Comment(1)
I did not try, but a good ideaMidi

© 2022 - 2024 — McMap. All rights reserved.