Accessing the Kubernetes API


When accessing the Kubernetes API for the first time, use the Kubernetes command-line tool, kubectl. To access a cluster, you need to know the location of the cluster and have credentials to access it.

Checking the location & credentials

[node1 kubelabs]$ kubectl config view
apiVersion: v1
- cluster:
    certificate-authority-data: DATA+OMITTED
  name: kubernetes
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
- name: kubernetes-admin

Directly accessing the REST API

The kubectl handles locating and authenticating to the API server. If you want to directly access the REST API with an HTTP client like curl or wget, or a browser, there are multiple ways you can locate and authenticate against the API server:

Using kubectl proxy

Running kubectl in proxy mode allows you to establish a secure connection to the Kubernetes API server without exposing it directly to the outside world. It acts as a bridge between your local machine and the Kubernetes cluster’s API server.

Here are a few reasons why you might want to run kubectl in proxy mode for API access:

To run kubectl in proxy mode, you can use the following command:

kubectl proxy

This will start a local proxy server that listens on a specified port (default is 8001). Once the proxy is running, you can access the Kubernetes API server by making requests to localhost or on the designated port.

Running kubectl in proxy mode provides a secure and convenient way to access the Kubernetes API server, allowing you to interact with and manage your cluster from your local machine.

The following command runs kubectl in a mode where it acts as a reverse proxy. It handles locating the API server and authenticating.

kubectl proxy --port=8080 &

Then you can explore the API with curl, wget, or a browser, like so:

curl http://localhost:8080/api/

The output is similar to this:

[node1 kubelabs]$ curl http://localhost:8080/api/
  "kind": "APIVersions",
  "versions": [
  "serverAddressByClientCIDRs": [
      "clientCIDR": "",
      "serverAddress": ""

Without kubectl proxy

  # Check all possible clusters, as you .KUBECONFIG may have multiple contexts:
kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'

# Select name of cluster you want to interact with from above output:
export CLUSTER_NAME="some_server_name"

# Point to the API server referring the cluster name
APISERVER=$(kubectl config view -o jsonpath="{.clusters[?(\"$CLUSTER_NAME\")].cluster.server}")

# Gets the token value
TOKEN=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 --decode)

# Explore the API with TOKEN
curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

Next »