Kubectl 端口在 shell 脚本中可靠转发

问题描述 投票:0回答:2

我在 shell 脚本中使用

kubectl port-forward
,但我发现它不可靠,或者没有及时出现:

kubectl port-forward ${VOLT_NODE} ${VOLT_CLUSTER_ADMIN_PORT}:${VOLT_CLUSTER_ADMIN_PORT} -n ${NAMESPACE} &
if [ $? -ne 0 ]; then
    echo "Unable to start port forwarding to node ${VOLT_NODE} on port ${VOLT_CLUSTER_ADMIN_PORT}"
    exit 1
fi
PORT_FORWARD_PID=$!

sleep 10

经常在我休眠10秒后,端口没有打开或者转发没有发生。有什么办法可以等待它准备好吗?像

kubectl wait
这样的东西是理想的,但也对 shell 选项开放。

kubernetes kubectl
2个回答
17
投票

我采纳了 @AkinOzer 的评论,并将其变成了这个示例,其中我转发了 postgresql 数据库的端口,这样我就可以制作数据库的

pg_dump

#!/bin/bash

set -e

localport=54320
typename=service/pvm-devel-kcpostgresql
remoteport=5432

# This would show that the port is closed
# nmap -sT -p $localport localhost || true

kubectl port-forward $typename $localport:$remoteport > /dev/null 2>&1 &

pid=$!
# echo pid: $pid

# kill the port-forward regardless of how this script exits
trap '{
    # echo killing $pid
    kill $pid
}' EXIT

# wait for $localport to become available
while ! nc -vz localhost $localport > /dev/null 2>&1 ; do
    # echo sleeping
    sleep 0.1
done

# This would show that the port is open
# nmap -sT -p $localport localhost

# Actually use that port for something useful - here making a backup of the
# keycloak database
PGPASSWORD=keycloak pg_dump --host=localhost --port=54320 --username=keycloak -Fc --file keycloak.dump keycloak

# the 'trap ... EXIT' above will take care of kill $pid

0
投票

我每天使用以下脚本:

  • 它使用
    kubectl
    自动查找您尝试转发到的服务的名称
  • 默认情况下,它采用服务中定义的端口并在本地使用相同的端口。
  • 您还可以选择要转发的端口(即
    service:to:from
  • 当您kill退出脚本时,它支持使用
    巧妙的技巧
    到所有
    <Ctrl-C>
    进行多个转发。

你像这样使用它:

k8sf mongodb mongodb4:27018:27017 kafka ...
#!/bin/zsh

declare -A service_map

NS="${NS:=`kubectl config view --minify --output 'jsonpath={..namespace}'`}"

for svc in "$@"; do
    if [[ $svc =~ : ]]; then
        local_port=
        remote_port=
        svc_conf_array=(${(s/:/)svc})
        svc_name=${svc_conf_array[1]}
        if (( ${#svc_conf_array[@]} > 2 )); then
            local_port=${svc_conf_array[2]}
            remote_port=${svc_conf_array[3]}
        else
            local_port=${svc_conf_array[2]}
            remote_port=`kubectl -n $NS get svc $svc_name -o json | jq '.spec.ports[0].port'`
        fi
        service_map[$svc_name]="$local_port:$remote_port"
    else
        port=`kubectl -n $NS get svc $svc -o json | jq '.spec.ports[0].port'`
        service_map[$svc]="$port:$port"
    fi
done

(trap 'kill 0' SIGINT; for svc pf in "${(@kv)service_map}"; do kubectl -n $NS port-forward --address 127.0.0.1 services/$svc "$pf" &; done; wait)
© www.soinside.com 2019 - 2024. All rights reserved.