macoskubectlportforwarding

kubectl port-forward multiple services


I have been trying to forward multiple ports with these commands:

kubectl port-forward deployment/service1 8080:8080 && kubectl port-forward deployment/service2 8081:8081

and

kubectl port-forward deployment/service1 8080:8080 || kubectl port-forward deployment/service2 8081:8081

it seems like it's only forwarding the first one with this output:

Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080

how can I make it to listen in the background and run the second command?


Solution

  • After the shell runs the first kubectl port-foward command, the process blocks and the second command would only ever begin after the first terminates (which it likely won't).

    To kubectl port-forward for multiple services, you would need to put each command into the background:

    kubectl port-forward deployment/service1 8080:8080 & \
    kubectl port-forward deployment/service2 8081:8081 &
    

    NOTE & is the bash instruction to run the command in the background (in a subshell). I've used \ to pretty-print the command on multiple lines but you can write multiple commands (separated by &) on a single line, e.g.

    echo "First" & echo "Second" & echo "Third" &