Unable to kubectl connect my kubernetes cluster

7/20/2018

With a Kubernetes cluster up and running and the ability to go to the master over ssh with ssh-keys and run kubectl commands there; I want to run kubectl commands on my local machine. So I try to setup the configuration, following the kubectl config:

kubectl config set-cluster mykube --server=https://<master-ip>:6443
kubectl config set-context mykube --cluster=mykube --user=mykube-adm
kubectl config set-credentials mykube-adm --client-key=path/to/private/keyfile 

Activate the context:

kubectl config use-context mykube

When I run a kubectl command:

kubectl get nodes

It returns:

The connection to the server localhost:8080 was refused - did you specify the right host or port?

The output of kubectl config view

apiVersion: v1
clusters:
- cluster:
    server: https://<master-ip>:6443
  name: mykubecontexts:
- context:
    cluster: mykube
    user: mykube-adm
  name: mykube
current-context: mykube
kind: Config
preferences: {}
users:
- name: mykube-adm
  user:
    client-key: path/to/private/keyfile
-- Joost Döbken
kubectl
kubernetes

1 Answer

7/22/2018

Unfortunately, above kubectl config file is incorrect. It seems an error appeared due to manual formatting or something else.

New line is missing in this part (name: mykubecontexts:):

clusters:
- cluster:
    server: https://<master-ip>:6443
  name: mykubecontexts:
- context:
    cluster: mykube
    user: mykube-adm
  name: mykube

Correct one is:

clusters:
- cluster:
    server: https://<master-ip>:6443
  name: mykube
contexts:
- context:
    cluster: mykube
    user: mykube-adm
  name: mykube

That's why cluster's name is mykubecontexts::

clusters:
- cluster:
    server: https://<master-ip>:6443
  name: mykubecontexts:

and that's why there is no context in it, because contexts: is not defined.

kubectl cannot find context mykube and switches to default one where server=localhost:8080 is by default.

kubectl config is located in ${HOME}/.kube/config file by default if --kubeconfig flag or $KUBECONFIG environment variable are not set.

Please correct it to the following one:

apiVersion: v1
clusters:
- cluster:
    server: https://<master-ip>:6443
  name: mykube
contexts:
- context:
    cluster: mykube
    user: mykube-adm
  name: mykube
current-context: mykube
kind: Config
preferences: {}
users:
- name: mykube-adm
  user:
    client-key: path/to/private/keyfile
-- nickgryg
Source: StackOverflow