kubectl: The connection to the server localhost:8080 was refused
The localhost:8080 fallback appears when kubectl has no kubeconfig. Check the merged config, KUBECONFIG in CI and in-cluster settings.

Introduction & Quick Summary
kubectl refuses to connect, and the address it names is almost never the address of a cluster:
The connection to the server localhost:8080 was refused - did you specify the right host or port?
Quick answer: kubectl has no cluster configuration, so it fell back to its built-in default. Check what it actually loaded:
kubectl config view --minify
kubectl config current-context
echo "KUBECONFIG=${KUBECONFIG:-<unset>}"
ls -l "${HOME}/.kube/config" 2>/dev/nulllocalhost:8080 is the historical default API server address compiled into the Kubernetes client libraries. When no kubeconfig file and no KUBERNETES_SERVICE_HOST are found, the client builds a config pointing at http://localhost:8080 and appends "did you specify the right host or port" to the connection error. Real clusters listen on 6443, 8443 or a NodePort, so this message is nearly always a client-side configuration problem. A genuine API server outage produces the same text only when the kubeconfig itself points at a local proxy.
Core Mechanics, Signatures & Reproducible Setup
kubectl resolves its cluster in a fixed order, and later sources do not override earlier ones — the first hit wins:
| Order | Source | Typical accident |
|---|---|---|
| 1 | --kubeconfig flag | a path from a script that no longer exists |
| 2 | merged KUBECONFIG files, colon-separated | first file wins per key, not per file |
| 3 | ${HOME}/.kube/config | HOME unset under sudo or in a container |
| 4 | the compiled default | http://localhost:8080 — the error you are reading |
Reproduce it deliberately:
KUBECONFIG=/nonexistent kubectl get nodes
# The connection to the server localhost:8080 was refused
env -u KUBECONFIG HOME=/tmp/empty kubectl version
# Client Version: v1.31.0
# The connection to the server localhost:8080 was refusedNotice that kubectl version still prints the client version first. The binary and its plugins are fine; only the connection is missing. That distinction matters because a broken kubectl installation and a missing kubeconfig look identical to a user in a hurry.
The same error appears from inside a Pod when a Go program calls rest.InClusterConfig() outside a cluster. That helper looks for KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT, then falls back to the same localhost default:
cfg, err := rest.InClusterConfig() // error: unable to load in-cluster configuration
if err != nil {
cfg, err = clientcmd.BuildConfigFromFlags("", kubeconfigPath)
}Key Comparison Table
Different connection failures mean different things, and mixing them up sends you to the wrong place:
| Message | Meaning | First check |
|---|---|---|
connection refused on localhost:8080 | no kubeconfig at all | kubectl config view |
connection refused on 10.0.0.5:6443 | kubeconfig points at a dead node | is the control plane up |
no such host | DNS name in the server field is wrong | nslookup the host |
i/o timeout | firewall, security group or VPN | curl -k https://host:6443/healthz |
Unauthorized | config loaded, credentials expired | token or client certificate |
Forbidden | authenticated, RBAC denies | kubectl auth can-i |
Where the kubeconfig comes from, and what to check when it is empty:
| Provider | Config path | Common break |
|---|---|---|
| minikube | ~/.kube/config, context minikube | file deleted after minikube delete |
| kind | ~/.kube/config, context kind-<name> | cluster renamed, old context left behind |
| k3s | /etc/rancher/k3s/k3s.yaml | not copied, or copied without sudo |
| Docker Desktop | ~/.kube/config | Kubernetes disabled in settings |
| EKS, GKE, AKS | ~/.kube/config after an auth command | credentials expired |
| CI runners | $KUBECONFIG from a secret | secret empty or base64-broken |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Read the merged config, not the file you think is used
kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}{"\n"}'
kubectl config get-contexts
kubectl config view --raw | head -40--minify shows only the active context's cluster, which is what kubectl will call. A file can contain six working clusters while the active context points at a deleted one. --raw prints secrets and certificate data that view normally redacts, which is useful when a certificate is present but malformed.
2. CI and containers: the environment is the prime suspect
# GitHub Actions
- run: |
mkdir -p ~/.kube
echo "${{ secrets.KUBE_CONFIG_B64 }}" | base64 -d > ~/.kube/config
chmod 600 ~/.kube/config
kubectl config current-context || kubectl config get-contextsFour failures account for most CI cases: the secret is empty, the base64 string is truncated by a newline, HOME is /root inside the container while the file was written to /home/runner, and the workflow runs sudo kubectl, which drops KUBECONFIG. Setting KUBECONFIG=/path/config explicitly at the job level fixes the last three at once. To inspect a kubeconfig or a service account token payload, decode it with the Base64 decoder; to check its structure line by line, paste it into the YAML validator.
3. Several contexts and the merge rules
kubectl config use-context kind-dev
kubectl config rename-context kind-dev dev
kubectl config set-context --current --namespace=paymentsWhen KUBECONFIG lists several files, kubectl merges them: the first file that defines a given cluster, user or context wins, and no file overrides another. Adding an updated kubeconfig at the end of the list therefore has no effect on names that already exist. Remove the stale file from the list or rewrite the entry.
4. Inside a Pod: in-cluster configuration
A workload that needs the API uses a mounted service account token. Three things break it:
automountServiceAccountToken: falseon the Pod or ServiceAccount;- a NetworkPolicy that blocks egress to the API server — the default deny often catches this;
- the token file rotated while a long-running process kept the old one in memory.
The API server address inside a cluster is https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT, which is normally the kubernetes.default.svc ClusterIP in the service CIDR range, not a public endpoint. Verify the routing with kubectl exec and a direct call before blaming RBAC:
kubectl run netcheck --rm -it --image=curlimages/curl --restart=Never -- \
curl -sk -o /dev/null -w '%{http_code}\n' \
https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT/healthz5. When the cluster really is down
From a machine with a correct kubeconfig, test the endpoint without kubectl:
SERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')
curl -sk -o /dev/null -w '%{http_code}\n' "$SERVER/healthz"503 means the API server is up but its backend (usually etcd) is not healthy. connection refused means nothing is listening — check the control plane node, the container that runs kube-apiserver, and whether a load balancer in front of it was rebuilt. On single-node setups the endpoint is often a Docker bridge address such as 172.18.0.2:6443; after a host reboot that address can change, and the kubeconfig keeps the old one. The CIDR calculator is handy for confirming whether an address belongs to the cluster's service or pod range.
6. kubectl proxy and the 8080 legacy
kubectl proxy listens on 127.0.0.1:8001 by default, not 8080. Older tooling hardcoded 8080, and a script that starts the proxy on 8080 while a different process already owns that port produces a refused connection that looks like a missing cluster. If you run a proxy deliberately, pin the port and pass the same port to clients: kubectl proxy --port=8080 --address=127.0.0.1.
Common Compilation/Runtime Mistakes & Version Gotchas
Editing ~/.kube/config by hand. One wrong indent makes the file unparseable, and kubectl reports a yaml error rather than the connection error — but a partially valid file with a missing cluster section produces exactly the localhost fallback. Keep a backup and validate the structure before saving.
Copying a kubeconfig without its CA and client data. --flatten merges the referenced files into one document; without it the config points at certificate paths that do not exist on the new machine.
Assuming sudo preserves the environment. sudo kubectl reads /root/.kube/config and ignores your KUBECONFIG. Use sudo -E or place the config where root looks.
Confusing a NodePort with the API endpoint. Clusters expose the API on 6443 internally; only some managed providers publish it. A NodePort in the 30000–32767 range plus localhost will never work from your laptop.
Version notes. Since client-go 1.x, the localhost fallback is deprecated but still present, and the hint text "did you specify the right host or port" is emitted only for that default. kubectl config view began redacting credentials in quiet mode years ago, so a config that looks empty in output may be complete. Client and server version skew beyond one minor release produces its own warning; it never causes this error.
Reference material: Configure access to multiple clusters and Organizing cluster access using kubeconfig files.
Official references
primary documentationThe Kubernetes documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Kubernetes guides
All Kubernetes guidesKubernetes 1.35: kubelet will not start on a cgroup v1 node
A 1.35 kubelet refuses a cgroup v1 host, and the removed pod-infra flag stops custom images. Check the kernel command line before the node pool.
Kubernetes: x509 certificate has expired or is not yet valid
kubeadm control plane certificates last one year. Renew them, restart the static pods, refresh kubeconfigs, and alert before the next expiry.
kubectl: metadata.resourceVersion: Invalid value: 0x0
The 0x0 error means an update carried no resourceVersion. Switch to apply or patch, or read the live object first, and keep versions out of Git.
no matches for kind in version: removed APIs and missing CRDs
kubectl cannot map the manifest to an endpoint. Either the API version was removed or the CRD is absent, and discovery tells you which.
More in Kubernetes
All Kubernetes guidesThe guides filed next to this one in Kubernetes, in library order.