.Kube

Kubernetes kubeconfig Configuration File

Learn how ~/.kube/config works, how kubectl selects clusters and credentials, how to manage contexts, and how to troubleshoot kubeconfig safely.

A kubeconfig is a YAML configuration format used by kubectl and compatible Kubernetes clients. It tells a client which Kubernetes API server to contact, which credentials to use, and which namespace and cluster combination should be selected by default.

The conventional location on Unix-like systems is ~/.kube/config. This is only the default location: a command can select another file with --kubeconfig, and the KUBECONFIG environment variable can specify one or more files.

How kubeconfig connects kubectl to a cluster

When a command does not explicitly select a context, kubectl reads the active current-context. That context refers to a named cluster entry, a named user entry, and optionally a default namespace.

The resulting lookup is:

kubectl
  └── kubeconfig
      └── current-context: development
          ├── cluster: development
          │   └── server and TLS trust settings
          ├── user: developer
          │   └── authentication settings
          └── namespace: development

This design makes it possible to switch between development, test, and production targets without rewriting every command. It also makes it important to verify the selected context before changing resources.

Configuration discovery and precedence

MechanismWhen it appliesExampleNotes
--kubeconfigWhen supplied to kubectlkubectl --kubeconfig "$HOME/.kube/team-config" get namespacesDirectly selects the file for that invocation.
KUBECONFIGWhen the environment variable is setexport KUBECONFIG="$HOME/.kube/config:$HOME/.kube/team-config"Can contain multiple files. Unix-like systems commonly separate them with a colon; Windows uses its platform-specific list separator.
Default pathWhen neither of the above selects a file~/.kube/configThe home directory is platform-specific. Use $HOME on many Unix-like shells and the appropriate home-directory expansion for your Windows shell.

A command-line --kubeconfig selection is the clearest way to target a supplied file for one operation. When KUBECONFIG names multiple files, Kubernetes clients can merge their clusters, users, contexts, and other configuration. Duplicate names can make the effective result confusing, so use unique and descriptive names.

kubeconfig structure

A minimal configuration has top-level fields such as apiVersion, kind, preferences, clusters, users, contexts, and current-context. The clusters, users, and contexts fields are named lists.

FieldPurposeTypical contentsSecurity considerations
apiVersionIdentifies the configuration API version.v1Not normally secret.
kindIdentifies the object type.ConfigNot normally secret.
preferencesClient preference settings.Often empty.Usually low sensitivity.
clustersNamed API server and TLS definitions.Server URL, CA data or CA file, proxy settings.Endpoints and trust configuration reveal infrastructure details.
usersNamed authentication definitions.Certificates, tokens, or an exec plugin.Frequently contains credentials or private keys.
contextsNamed combinations of cluster, user, and namespace.development using user developer.Names can reduce operational mistakes but do not grant permissions.
current-contextSelects the default context.developmentA wrong value can send commands to the wrong cluster.

For example:

apiVersion: v1
kind: Config
clusters:
- name: development
  cluster:
    server: https://api.dev.example.invalid:6443
    certificate-authority: /home/user/.kube/dev-ca.crt
users:
- name: developer
  user:
    client-certificate: /home/user/.kube/developer.crt
    client-key: /home/user/.kube/developer.key
contexts:
- name: development
  context:
    cluster: development
    user: developer
    namespace: development
current-context: development

Cluster entries and TLS

A cluster entry contains the Kubernetes API server endpoint in the server field, such as https://api.dev.example.invalid:6443. It can also define how the client verifies the server's TLS certificate.

  • certificate-authority points to a local certificate authority file.
  • certificate-authority-data contains embedded, usually base64-encoded, certificate authority data.
  • insecure-skip-tls-verify: true disables server certificate verification.
  • proxy-url specifies a proxy when the client must reach the API server through one.

Prefer the correct CA file or CA data. Disabling TLS verification allows a client to accept an untrusted or impersonated server and should not be used as a routine fix for certificate errors.

User authentication entries

A kubeconfig user is a named set of client credentials. The name is a kubeconfig label; it is not necessarily the username or identity recognized by Kubernetes RBAC.

MethodRelevant fieldsTypical useRisks and operational notes
Client certificateclient-certificate and client-key, or client-certificate-data and client-key-dataCertificate-based authentication.Private keys are sensitive. Embedded data makes copying easier but increases exposure if the config is shared.
Bearer tokentoken or tokenFileStatic or issued token authentication.Plaintext tokens can provide access to anyone who reads the file. Rotate expired or exposed tokens.
Exec credential pluginexec, including a command and argumentsCloud-provider or external identity authentication.The client runs an external command. Verify the command and its source. The plugin can obtain or refresh short-lived credentials.

With an exec credential plugin, kubectl invokes the configured command when credentials are needed. Depending on the plugin, it may return a short-lived token or certificate and refresh it after expiration. A failed command, missing binary, expired cloud login, or incorrect environment can produce an authentication error.

Contexts and namespaces

A context is a named selection of a cluster, a user, and an optional namespace.

Context fieldReferencesEffect on kubectl commands
clusterA name in clustersSelects the API server and its TLS settings.
userA name in usersSelects the credentials presented to the API server.
namespaceA Kubernetes namespace nameProvides the default namespace for namespaced commands.

A context namespace is only a default. A command-level option such as --namespace other-team overrides it for that command. Cluster-scoped resources are not affected by namespace defaults.

Inspecting configuration safely

TaskCommandExpected resultSafety note
Display the active contextkubectl config current-contextPrints the current context name.Safe and low exposure.
List contextskubectl config get-contextsShows context, cluster, authentication user, and namespace columns.Review the asterisk marking the active context.
View effective configurationkubectl config viewShows the configuration selected by the current file settings.Review output before logging or sharing it.
View raw credential fieldskubectl config view --rawPreserves raw credential fields instead of redacting or transforming them.Highly sensitive; do not paste into tickets or chat.
Inspect a particular filekubectl --kubeconfig "$HOME/.kube/team-config" config viewReads that file rather than relying on the default.Useful for isolating file-selection problems.

Use kubectl config subcommands for routine changes because they handle the YAML structure for you. Direct YAML editing is appropriate when importing a carefully prepared configuration or making a change not supported by a convenient command, but preserve indentation, valid YAML syntax, correct names, and file permissions. Make a protected backup before editing.

A flattened kubeconfig embeds referenced certificate and key data to make the configuration self-contained. Flattened output can be convenient for transfer, but it may expose private keys and should be treated as especially sensitive.

Creating and managing entries

These commands create or update named entries in the selected kubeconfig:

kubectl config set-cluster development \
  --server=https://api.dev.example.invalid:6443 \
  --certificate-authority="$HOME/.kube/dev-ca.crt"

kubectl config set-credentials developer \
  --client-certificate="$HOME/.kube/developer.crt" \
  --client-key="$HOME/.kube/developer.key"

kubectl config set-context development \
  --cluster=development \
  --user=developer \
  --namespace=development

Activate a context and set its namespace with:

kubectl config use-context development
kubectl config set-context --current --namespace=development

Context names should clearly identify the environment and, when useful, the account or namespace, for example dev-developer, test-readonly, or prod-operator. Clear names are an operational safeguard, not an authorization mechanism.

Configuration entries can also be renamed or deleted with kubectl config rename-context, kubectl config delete-context, kubectl config delete-cluster, and kubectl config delete-user. Deleting a context does not necessarily delete the cluster or user entry it referenced. Remove unused entries separately only after confirming that no other context needs them.

Multiple clusters and files

Keep development and production credentials separate when possible. A separate file can be selected without replacing the normal configuration:

kubectl --kubeconfig "$HOME/.kube/team-config" get namespaces

On Unix-like systems, multiple files can be merged through KUBECONFIG:

export KUBECONFIG="$HOME/.kube/config:$HOME/.kube/team-config"
kubectl config view

The merged view may contain entries from both files. Duplicate names are hazardous because one entry can override or combine with another according to kubeconfig loading rules. Use unique names such as company-prod, company-dev, prod-readonly, and dev-admin. Inspect each input file separately when the merged result is unexpected.

Security and operational practices

  • Set restrictive permissions where supported, for example chmod 600 "$HOME/.kube/config".
  • Do not commit kubeconfig files, tokens, private keys, or flattened output to source control.
  • Do not share a complete configuration unless every credential and embedded certificate has been reviewed and exposure is acceptable.
  • Use separate, low-privilege credentials for routine work and production administration.
  • Use prominent production context names and check them before changes.
  • Investigate TLS problems instead of broadly enabling insecure-skip-tls-verify.
  • Review exec plugin commands because a client may execute them locally to obtain credentials.

A kubeconfig grants only the access represented by its credentials. After authentication, Kubernetes authorization, commonly RBAC, determines whether the identity may perform a requested action on a resource. Possessing a configuration does not automatically mean that every operation is allowed.

Validation and diagnosis

Start with non-destructive checks:

kubectl config current-context
kubectl config get-contexts
kubectl config view
kubectl get namespaces

The last command is a harmless request when your account is allowed to list namespaces. It tests more than local YAML parsing: the selected endpoint must be reachable, TLS must validate, credentials must authenticate, and authorization must permit the request.

SymptomLikely causeVerification stepResolution
kubectl targets an unexpected clusterWrong current context, unexpected KUBECONFIG, or an explicit command override.Run kubectl config current-context, kubectl config get-contexts, and inspect command arguments and KUBECONFIG.Select the intended context or explicitly choose the intended file and context.
Unable to connect to the serverIncorrect endpoint, unavailable API server, DNS, VPN, firewall, or network problem.Inspect the active cluster's server value and test network access; try kubectl get namespaces.Correct the endpoint or restore network access.
x509 certificate verification errorIncorrect or missing CA, changed server certificate, or TLS-intercepting proxy.Inspect CA settings and confirm the expected endpoint and CA with the cluster administrator.Install the correct CA or resolve the certificate or proxy issue. Do not immediately disable verification.
Unauthorized or authentication requiredExpired token, invalid client certificate, failed exec plugin, or credentials for another cluster.Identify the active context's user and check the plugin or credential validity.Refresh or replace credentials, repair the plugin, or select the correct context.
Forbidden after successful connectionThe authenticated identity lacks RBAC permission, or the namespace or resource is wrong.Confirm context and namespace; where permitted, use kubectl auth can-i.Use the correct namespace or request the least-privilege RBAC grant required.
Entries appear missingA different file is selected, multiple files merge unexpectedly, or names conflict.Inspect KUBECONFIG, run kubectl config view, and inspect each input file separately.Correct the configuration source and use unique entry names.

Exam-relevant notes

  • current-context selects the default context; it is not the same thing as the current namespace alone.
  • A context connects a cluster entry to a user entry and may define a namespace.
  • --kubeconfig, then KUBECONFIG, and finally the conventional default location determine which configuration source is used.
  • A kubeconfig user name is a local configuration label and should not automatically be assumed to be the Kubernetes RBAC username.
  • Authentication answers “Who are you?”; RBAC authorization answers “What may you do?”
  • Deleting a context does not necessarily remove its referenced cluster or user.
  • certificate-authority-data embeds trust material, while certificate-authority points to a file.
  • insecure-skip-tls-verify weakens server identity verification and is not a safe general troubleshooting solution.

For related configuration details, return to Kubernetes kubeconfig configuration and use the inspection and context checks before making changes to a cluster.