Sign In

Curriculum 20: Kubeconfig & Contexts

Multiple Clusters

15 min · 35 XP

Working with Multiple Clusters

In real-world environments, you typically manage several clusters: development, staging, and production. Kubeconfig makes it straightforward to add and switch between them without juggling separate config files.

Adding a New Cluster

Use kubectl config set-cluster and kubectl config set-credentials to register a new cluster and user, then create a context linking them together.

# Add a staging cluster
kubectl config set-cluster staging-cluster \
  --server=https://staging.example.com:6443 \
  --certificate-authority=/path/to/staging-ca.crt

# Add credentials for the staging cluster
kubectl config set-credentials staging-admin \
  --client-certificate=/path/to/staging-cert.crt \
  --client-key=/path/to/staging-key.key

# Create a context that ties them together
kubectl config set-context staging \
  --cluster=staging-cluster \
  --user=staging-admin \
  --namespace=default

Switching Between Clusters

Once your contexts are defined, switching is a single command:

# Switch to the staging context
kubectl config use-context staging

# Verify you switched
kubectl config current-context
# Output: staging

# Run a command against a different context without switching
kubectl get pods --context=prod

A Typical Multi-Cluster Setup

# See all available contexts
kubectl config get-contexts

# Example output:
# CURRENT   NAME      CLUSTER           AUTHINFO        NAMESPACE
# *         dev       dev-cluster       dev-admin       default
#           staging   staging-cluster   staging-admin   default
#           prod      prod-cluster      prod-readonly   production

The asterisk marks your active context. You can quickly move between dev, staging, and prod by switching contexts rather than editing config files manually.

Key Takeaways

  • Use set-cluster, set-credentials, and set-context to add new environments
  • use-context switches your active cluster
  • The --context flag lets you target a different cluster for a single command