Running multi Port-forward with tmux | by mobin shaterian | Oct, 2024

This guide demonstrates how to set up and use tmux for multi-port forwarding in Kubernetes environments. Tmux is a terminal multiplexer that allows users to manage multiple terminal sessions within a single window. By combining tmux with Kubernetes port-forwarding, you can efficiently manage multiple port-forward connections simultaneously, which is particularly useful for complex microservices architectures or when working with multiple pods across different namespaces.

1. Install tmux using the package manager (e.g., `sudo apt install tmux`).
2. Create a Bash script to automate the process:
— Set up variables for the tmux session name, Kubernetes namespaces, pod name patterns, and port mappings.
— Create a new tmux session.
— Iterate through the configured namespaces and pods, creating new windows for each.
— Use kubectl commands to find the appropriate pods and set up port-forwarding.
— Attach to the tmux session to view and manage all port-forward connections.
3. Make the script executable using `chmod +x script_name.sh`.
4. Run the script to start the tmux session with multiple port-forward connections.

This approach streamlines the process of managing multiple port-forward connections, making it easier to work with complex Kubernetes deployments and access various services simultaneously.

sudo apt install tmux

Creating and executing a Bash script is a straightforward process. Here’s a step-by-step guide to help you get started:

  1. Open a terminal.
  2. Create a new file using a text editor like nano, vim, or gedit. For example, using nano:nano myscript.sh
  3. Write your script. For a simple example, you can add the following lines to print “Hello, World!”#!/bin/bash echo "Hello, World!"
  4. Save and exit the editor. In nano, you can do this by pressing Ctrl + X, then Y, and Enter.

Change the file permissions to make it executablechmod +x myscript.sh

Run the script by typing:./myscript.sh

#!/bin/bash
SESSION="port_forward"

NAMESPACE=("name-space" "name-space" )
PATTERN=("podname-" "podname-" )
PORT_MAPPINGS=("8081:9000" "8082:9000")

# Start a new tmux session
tmux new-session -d -s $SESSION

# Create three windows (tabs)
for i in 0 1 2 3 4 5; do
tmux new-window -t $SESSION:$((i+1))
tmux send-keys -t $SESSION:$((i+1)) "kubectl get pods -n ${NAMESPACE[$i]} | grep ${PATTERN[$i]}" C-m
POD_NAME=$(kubectl get pods -n ${NAMESPACE[$i]} | grep ${PATTERN[$i]} | awk '{print $1}')
tmux send-keys -t $SESSION:$((i+1)) "kubectl port-forward $POD_NAME ${PORT_MAPPINGS[$i]} -n ${NAMESPACE[$i]}" C-m
done

# Attach to the tmux session
tmux attach-session -t $SESSION