Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubectl port forward reliably in a shell script

I am using kubectl port-forward in a shell script but I find it is not reliable, or doesn't come up in time:

kubectl port-forward ${VOLT_NODE} ${VOLT_CLUSTER_ADMIN_PORT}:${VOLT_CLUSTER_ADMIN_PORT} -n ${NAMESPACE} &
if [ $? -ne 0 ]; then
    echo "Unable to start port forwarding to node ${VOLT_NODE} on port ${VOLT_CLUSTER_ADMIN_PORT}"
    exit 1
fi
PORT_FORWARD_PID=$!

sleep 10

Often after I sleep for 10 seconds, the port isn't open or forwarding hasn't happened. Is there any way to wait for this to be ready. Something like kubectl wait would be ideal, but open to shell options also.

like image 623
eeijlar Avatar asked Mar 23 '26 17:03

eeijlar


1 Answers

I took @AkinOzer's comment and turned it into this example where I port-forward a postgresql database's port so I can make a pg_dump of the database:

#!/bin/bash

set -e

localport=54320
typename=service/pvm-devel-kcpostgresql
remoteport=5432

# This would show that the port is closed
# nmap -sT -p $localport localhost || true

kubectl port-forward $typename $localport:$remoteport > /dev/null 2>&1 &

pid=$!
# echo pid: $pid

# kill the port-forward regardless of how this script exits
trap '{
    # echo killing $pid
    kill $pid
}' EXIT

# wait for $localport to become available
while ! nc -vz localhost $localport > /dev/null 2>&1 ; do
    # echo sleeping
    sleep 0.1
done

# This would show that the port is open
# nmap -sT -p $localport localhost

# Actually use that port for something useful - here making a backup of the
# keycloak database
PGPASSWORD=keycloak pg_dump --host=localhost --port=54320 --username=keycloak -Fc --file keycloak.dump keycloak

# the 'trap ... EXIT' above will take care of kill $pid
like image 55
Peter V. Mørch Avatar answered Mar 25 '26 16:03

Peter V. Mørch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!