rideswitch
rideswitch

Reputation: 1521

how to undo a kubectl port-forward

If I forwarded a port using

kubectl port-forward mypod 9000:9000

How can I undo that so that I can bind port 9000 with another program?
Additionally, how can I test to see what ports are forwarded?

Upvotes: 87

Views: 99451

Answers (8)

Demetry Pascal
Demetry Pascal

Reputation: 554

I use screen.

To start (Ansible task):

    - name: web port forward for debugging
      vars:
        command: "kubectl port-forward --address 0.0.0.0 web-0 8895:1443 --namespace nss &"
      shell:
        cmd: |
          (screen -S "kube-port-forward" -dm {{ command }}) || screen -S "kube-port-forward" -dm '{{ command }}'

To stop:

screen -X -S "kube-port-forward" quit || true

Notes:

  • this command really works only if I will try the main command without quotes, get error and try with quotes, I dunno why it is so

Upvotes: 0

KardiffInker
KardiffInker

Reputation: 101

To kill the specific process the command I use is:

ps -aux | grep -i kubectl

I then look for the specific port forward for example the output should look like the following:

User 21625 4.8 0.6 745868 51112 pts/0 Sl 09:29 0:09 kubectl port-forward -n namespace service/servicename 8898:80

Where 21625 is the process number:

kill -9 21625

You should then see

[1]+ Killed kubectl port-forward -n namespace service/service 8898:80

In the terminal running that process indicating that the process doing the port forward has now been killed.

Upvotes: 1

todd_dsm
todd_dsm

Reputation: 1076

Just use pgrep; this can be dropped into a script and it will kill all PIDs that are port-forwarding:

###---
### kill all kubectl port-forward
###---
echo "Dumping all kubectl port-forward PIDs..."
while read -r myPID; do
    kill -9 "$myPID"
done < <(pgrep kubectl)

This will usually return only port-forwarding PIDs but realistically, it could be any long-running kubectl process so - be careful.

Upvotes: 2

fizmax
fizmax

Reputation: 577

If it runs in background, consider using pkill to kill processes by their names. Example:

pkill -f "port-forward"

Upvotes: 22

Huang Jinlong
Huang Jinlong

Reputation: 1044

$ ps -ef|grep port-forward

wyyl1      2013886       1  0 02:18 ?        00:00:10 kubectl port-forward svc/prometheus 9090:9090
wyyl1      2253978 2178606  0 07:58 pts/2    00:00:00 grep --color=auto port-forward

$ kill -9 2013886

Upvotes: 33

anrajme
anrajme

Reputation: 905

ps aux | grep -i kubectl | grep -v grep | awk {'print $2'} | xargs kill

Upvotes: 6

Doctor
Doctor

Reputation: 7996

If it was launch in the background you can use the fg command to access it and then use ctrl + C

Upvotes: 28

Alex Robinson
Alex Robinson

Reputation: 13397

The port is only forwarded while the kubectl process is running, so you can just kill the kubectl process that's forwarding the port. In most cases that'll just mean pressing CTRL+C in the terminal where the port-forward command is running.

Upvotes: 105

Related Questions