kubectl 端口转发多个服务

fxf*_*fxf 10 macos portforwarding kubectl

我一直在尝试使用以下命令转发多个端口:

kubectl port-forward deployment/service1 8080:8080 && kubectl port-forward deployment/service2 8081:8081
Run Code Online (Sandbox Code Playgroud)

kubectl port-forward deployment/service1 8080:8080 || kubectl port-forward deployment/service2 8081:8081
Run Code Online (Sandbox Code Playgroud)

看起来它只转发带有以下输出的第一个:

Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它在后台监听并运行第二个命令?

Daz*_*kin 14

shell 运行第一个kubectl port-foward命令后,进程会阻塞,第二个命令只会在第一个命令终止后才开始(很可能不会)。

对于kubectl port-forward多个服务,您需要将每个命令放入后台:

kubectl port-forward deployment/service1 8080:8080 & \
kubectl port-forward deployment/service2 8081:8081 &
Run Code Online (Sandbox Code Playgroud)

注意 &是在后台(在子 shell 中)运行命令的 bash 指令。我曾经\在多行上漂亮地打印命令,但您可以&在一行上编写多个命令(用 分隔),例如

echo "First" & echo "Second" & echo "Third" &
Run Code Online (Sandbox Code Playgroud)


ale*_*_si 8

这是我的两分钱和一个 shell 脚本示例:

# Push commands in the background, when the script exits, the commands will exit too
kubectl --context "$SELECTED_CONTEXT" --namespace "$SELECTED_NS" port-forward service/service1 1433:1433 & \
kubectl --context "$SELECTED_CONTEXT" --namespace "$SELECTED_NS" port-forward service/service2 80:80 & \

echo "Press CTRL-C to stop port forwarding and exit the script"
wait
Run Code Online (Sandbox Code Playgroud)