Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readKubernetes
#kubernetes#kubectl#kubeconfig#ci
Bold white headline reading NO KUBECONFIG with a kubectl client crate reaching an amber 8080 gate while a cyan cluster sits far right.

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:

bash
kubectl config view --minify kubectl config current-context echo "KUBECONFIG=${KUBECONFIG:-<unset>}" ls -l "${HOME}/.kube/config" 2>/dev/null

localhost: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:

OrderSourceTypical accident
1--kubeconfig flaga path from a script that no longer exists
2merged KUBECONFIG files, colon-separatedfirst file wins per key, not per file
3${HOME}/.kube/configHOME unset under sudo or in a container
4the compiled defaulthttp://localhost:8080 — the error you are reading

Reproduce it deliberately:

bash
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 refused

Notice 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:

go
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:

MessageMeaningFirst check
connection refused on localhost:8080no kubeconfig at allkubectl config view
connection refused on 10.0.0.5:6443kubeconfig points at a dead nodeis the control plane up
no such hostDNS name in the server field is wrongnslookup the host
i/o timeoutfirewall, security group or VPNcurl -k https://host:6443/healthz
Unauthorizedconfig loaded, credentials expiredtoken or client certificate
Forbiddenauthenticated, RBAC denieskubectl auth can-i

Where the kubeconfig comes from, and what to check when it is empty:

ProviderConfig pathCommon break
minikube~/.kube/config, context minikubefile deleted after minikube delete
kind~/.kube/config, context kind-<name>cluster renamed, old context left behind
k3s/etc/rancher/k3s/k3s.yamlnot copied, or copied without sudo
Docker Desktop~/.kube/configKubernetes disabled in settings
EKS, GKE, AKS~/.kube/config after an auth commandcredentials expired
CI runners$KUBECONFIG from a secretsecret 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

bash
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-contexts

Four 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

bash
kubectl config use-context kind-dev kubectl config rename-context kind-dev dev kubectl config set-context --current --namespace=payments

When 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: false on 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/healthz

5. When the cluster really is down

From a machine with a correct kubeconfig, test the endpoint without kubectl:

bash
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 documentation

The Kubernetes documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Kubernetes work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Kubernetes guides

More in Kubernetes

All Kubernetes guides

The guides filed next to this one in Kubernetes, in library order.