Script for running port-forward automatically

Viewed 3104

I want to create a script that will run port-forwarding for a pod automatically, for specific pod name(app3, I've multiple apps in this namespace and I need to run just for app3 ) when I run this script.

e.g.

kubectl port-forward pods/app3-86499b66d-dfwf7 8000:8000 -n web

I've started with

kubectl get pod -n webide-system | grep app3

The output is:

app3-86499b66d-dfwf7 1/1 Running 0 18h

However,Im not sure how to take the output, which is the pod name and run the port forwarding to it The following in bold is constant

pods/app3-86499b66d-dfwf7

And this is changing for each deployment

-86499b66d-dfwf7

Any idea how to make it works with a script?

2 Answers
POD_NAME=`kubectl get pod -n webide-system | grep app3 | sed 's/ .*//'`

kubectl port-forward pods/$POD_NAME  8000:8000  -n web

The answer provided by @Beta is correct, but I would like to show you yet another approach.

You can expose the pod using a Service:

$ kubectl expose pod app3-86499b66d-dfwf7 --port 8000 --name app3
service/app3 exposed

But in this case the pod is referenced using pod-template-hash, so when recreated, the service won't longer work.

This is why much better option is to expose a deployment:

$ kubectl expose deployment app3 --port 8000
service/app3 exposed

And now you can access it using pord-forward funcitonality like following:

$ kubectl port-forward service/app3 8000:8000
Forwarding from 127.0.0.1:8000 -> 8000
Forwarding from [::1]:8000 -> 8000

The second approach additionally takes case of loadbalancing, so if you had more than 1 replica, it would handle traffic distribution for you.

Related