How to Deploy to GKE in GCP: Step-by-Step Guide
To deploy to
GKE in GCP, first create a Kubernetes cluster using gcloud container clusters create. Then, configure kubectl to connect to the cluster and deploy your app with kubectl apply -f using your deployment YAML file.Syntax
Here is the basic syntax to deploy an app to GKE:
gcloud container clusters create [CLUSTER_NAME]: Creates a Kubernetes cluster.gcloud container clusters get-credentials [CLUSTER_NAME]: Configures your localkubectlto connect to the cluster.kubectl apply -f [DEPLOYMENT_FILE].yaml: Deploys your app using a Kubernetes YAML file.
bash
gcloud container clusters create CLUSTER_NAME --zone ZONE gcloud container clusters get-credentials CLUSTER_NAME --zone ZONE kubectl apply -f DEPLOYMENT_FILE.yaml
Example
This example shows how to create a cluster, connect to it, and deploy a simple nginx app.
bash
gcloud container clusters create my-cluster --zone us-central1-a gcloud container clusters get-credentials my-cluster --zone us-central1-a kubectl apply -f - <<EOF apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment spec: replicas: 2 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.21 ports: - containerPort: 80 EOF
Output
Creating cluster my-cluster...done.
Fetching cluster endpoint and auth data.
deployment.apps/nginx-deployment created
Common Pitfalls
Common mistakes when deploying to GKE include:
- Not setting the correct zone or region when creating or accessing the cluster.
- Forgetting to configure
kubectlwithget-credentials, causing connection errors. - Using incorrect YAML syntax or missing required fields in deployment files.
- Not having the right permissions or roles in GCP to create clusters or deploy apps.
bash
### Wrong: Missing get-credentials step kubectl apply -f deployment.yaml ### Right: Include get-credentials gcloud container clusters get-credentials my-cluster --zone us-central1-a kubectl apply -f deployment.yaml
Quick Reference
Remember these quick tips:
- Always specify the cluster zone or region.
- Use
gcloud container clusters get-credentialsbefore deploying. - Validate your YAML files with
kubectl apply --dry-run=client. - Check your GCP IAM permissions if you face access issues.
Key Takeaways
Create your GKE cluster with the correct zone using gcloud commands.
Configure kubectl to connect to your cluster before deploying.
Deploy your app using kubectl apply with a valid YAML file.
Validate YAML and check permissions to avoid common errors.
Use gcloud and kubectl commands in the right order for smooth deployment.