How to Use kubectl with GKE in Google Cloud Platform
To use
kubectl with GKE in GCP, first authenticate with your Google Cloud account using gcloud auth login. Then configure access to your GKE cluster by running gcloud container clusters get-credentials [CLUSTER_NAME] --zone [ZONE]. After this, you can run kubectl commands to manage your cluster.Syntax
The main commands to use kubectl with GKE are:
gcloud auth login: Logs you into your Google Cloud account.gcloud container clusters get-credentials [CLUSTER_NAME] --zone [ZONE]: Fetches cluster credentials and configureskubectlto use the cluster.kubectl [command]: Runs Kubernetes commands on your GKE cluster.
bash
gcloud auth login gcloud container clusters get-credentials [CLUSTER_NAME] --zone [ZONE] kubectl get pods
Example
This example shows how to authenticate, configure access to a GKE cluster named my-cluster in zone us-central1-a, and list all pods in the default namespace.
bash
gcloud auth login gcloud container clusters get-credentials my-cluster --zone us-central1-a kubectl get pods
Output
NAME READY STATUS RESTARTS AGE
example-pod-1234567890 1/1 Running 0 5m
Common Pitfalls
Common mistakes when using kubectl with GKE include:
- Not running
gcloud auth loginfirst, so authentication fails. - Forgetting to run
gcloud container clusters get-credentials, sokubectldoes not know which cluster to talk to. - Using the wrong cluster name or zone, causing errors connecting to the cluster.
- Running
kubectlcommands without proper permissions.
bash
Wrong: kubectl get pods Right: gcloud auth login gcloud container clusters get-credentials my-cluster --zone us-central1-a kubectl get pods
Quick Reference
| Command | Description |
|---|---|
| gcloud auth login | Authenticate your Google Cloud account |
| gcloud container clusters get-credentials [CLUSTER_NAME] --zone [ZONE] | Configure kubectl to use your GKE cluster |
| kubectl get pods | List pods in the current namespace |
| kubectl apply -f [file.yaml] | Apply configuration from a YAML file |
| kubectl describe node [NODE_NAME] | Show details about a node |
Key Takeaways
Always authenticate with Google Cloud using gcloud before using kubectl with GKE.
Use gcloud container clusters get-credentials to configure kubectl for your cluster.
Verify cluster name and zone to avoid connection errors.
kubectl commands manage your Kubernetes resources once configured.
Check permissions if kubectl commands fail due to access issues.