0
0
GcpHow-ToBeginner · 4 min read

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 configures kubectl to 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 login first, so authentication fails.
  • Forgetting to run gcloud container clusters get-credentials, so kubectl does not know which cluster to talk to.
  • Using the wrong cluster name or zone, causing errors connecting to the cluster.
  • Running kubectl commands 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

CommandDescription
gcloud auth loginAuthenticate your Google Cloud account
gcloud container clusters get-credentials [CLUSTER_NAME] --zone [ZONE]Configure kubectl to use your GKE cluster
kubectl get podsList 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.