Running multi Port-forward with tmux

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.

Summary:

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.

Install tmux

bash
sudo
apt install tmux

Make bash file

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

1. Create a Bash Script

  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.

2. Make the Script Executable

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

3. Execute the Script

Run the script by typing:./myscript.sh

4. Script

bash
#!/bin/bashSESSION="port_forward"NAMESPACE=("name-space" "name-space" )PATTERN=("podname-"
"podname-" )PORT_MAPPINGS=("8081:9000" "8082:9000")# Start a new tmux sessiontmux 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-mdone# Attach to the
tmux sessiontmux attach-session -t $SESSION