Skip to content

Instantly share code, notes, and snippets.

@Donnerbart
Created July 9, 2024 18:29
Show Gist options
  • Save Donnerbart/75e130c91803e1343c46b2b52e456d7a to your computer and use it in GitHub Desktop.
Save Donnerbart/75e130c91803e1343c46b2b52e456d7a to your computer and use it in GitHub Desktop.
K8s port forwarding helper scripts
#!/bin/bash
APP_NAME="My Application"
SERVICE_NAME="my-service"
POD_LABEL_SELECTOR=app.kubernetes.io/name=my-app
PORT=9400
# check if port-forwarding is already running
if pgrep -f "kubectl port-forward svc/$SERVICE_NAME" > /dev/null; then
echo "Port forwarding is already active."
exit 0
fi
echo "Port forwarding not active. Checking if $APP_NAME pod is running..."
# wait until the pod is ready
echo "$APP_NAME pod is running. Checking readiness..."
until kubectl get pods -l "${POD_LABEL_SELECTOR}" -o jsonpath='{.items[0].status.containerStatuses[0].ready}' | grep -q "true"; do
echo "Waiting for $APP_NAME pod to become ready..."
sleep 1
done
# start port forwarding
echo "$APP_NAME pod is ready. Starting port forwarding..."
kubectl port-forward svc/$SERVICE_NAME $PORT:$PORT >/dev/null &
#!/bin/bash
SERVICE_NAME="my-service"
PID=$(pgrep -f "kubectl port-forward svc/$SERVICE_NAME")
if [[ -n $PID ]]; then
echo "Killing port forwarding (PID: $PID)..."
kill "$PID"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment