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

痞子三分冷 提交于 2019-12-20 09:46:19

问题


I have exposed a service on an external port on all nodes in a kubernetes cluster from:

kubectl create -f nginx-service.yaml

You have exposed your service on an external port on all nodes in your cluster. If you want to expose this service to the external internet, you may need to set up firewall rules for the service port(s) (tcp:30002) to serve traffic.

See http://releases.k8s.io/release-1.2/docs/user-guide/services-firewalls.md for more details. service "nginx-service" created.`

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


回答1:


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".




回答2:


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




回答3:


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.




回答4:


...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


来源:https://stackoverflow.com/questions/37648553/is-there-anyway-to-get-the-external-ports-of-the-kubernetes-cluster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!