Is there anyway to get the external ports of the kubernetes cluster

与世无争的帅哥 提交于 2019-12-02 19:05:00

kubectl get svc --all-namespaces -o go-template='{{range .items}}{{range.spec.ports}}{{if .nodePort}}{{.nodePort}}{{"\n"}}{{end}}{{end}}{{end}}'

This gets all services in all namespaces, and does basically: "for each service, for each port, if nodePort is defined, print nodePort".

If you view your service using kubectl describe service NAME it should show you what port was assigned (in the NodePort field).

rajdeepbs29

I hope this answer is short and simple:

kubectl describe service --all-namespaces | grep -i nodeport

But, using go template is the ideal option and can be used to extract more details.

...and you can perform the same solution alternatively with a JsonPath...

  • get the external Port (the "nodePort") of myservice corresponding to the internal port 1234

    kubectl get svc myservice -o=jsonpath='{.spec.ports[?(@.port==1234)].nodePort}
    
  • get a list of all IPs of the Nodes underlying your cluster

    kubectl get node -o=jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
    

Obviously this information can easily be combined into a convenient bash script to suit any specific needs...

#!/bin/bash
#
# discoverService - extract the externally visible Node-IP and port for a specific Service in Kubernetes
#
KUBECTL=kubectl
#
if [[ $# < 2 || "$1" == "-h" ]]
    then
    echo discoverService SERVICENAME INTERNALPORT
    exit -1
fi
SERVICENAME=$1
INTERNALPORT=$2

EXTPORT=`${KUBECTL} get svc $SERVICENAME -o=jsonpath="{.spec.ports[?(@.port==${INTERNALPORT})].nodePort}"`

EXTIP=`${KUBECTL} get node -o=jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}'`


if [[ -z $EXTPORT ]]
    then
    echo -e "ERROR: service=$SERVICENAME internal-port=$INTERNALPORT not found.\n"
    exit -2
elif [[ -z $EXTIP ]]
    then
    echo -e "ERROR: could not retrieve underlying node IPs.\n"
    exit -2
fi
# Success...
echo $EXTIP:$EXTPORT
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!