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

6/6/2016

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?

-- kevin
kubectl
kubernetes

4 Answers

8/31/2016

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

-- Tim Hockin
Source: StackOverflow

6/6/2016

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

-- Robert Bailey
Source: StackOverflow

6/10/2019

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.

-- rajdeepbs29
Source: StackOverflow

2/15/2019

...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
-- Ichthyo
Source: StackOverflow