Cheatsheet: kubectl

Basic Commands

Show cluster info

kubectl cluster-info

List all resources in the cluster

kubectl get all --all-namespaces

List all pods in the current namespace

kubectl get pods

List all resources of a type

kubectl get <resource_type>

Describe a resource

kubectl describe <resource_type> <resource_name>

Get resource in a specific namespace

kubectl get <resource_type> -n <namespace>

Create resource from file

kubectl apply -f <file_name>

Delete a resource

kubectl delete <resource_type> <resource_name>

Pod Management

Get logs for a pod

kubectl logs <pod_name>

Get logs for a specific container in a pod

kubectl logs <pod_name> -c <container_name>

Execute a command in a pod

kubectl exec -it <pod_name> -- /bin/sh

Port-forward a pod to localhost

kubectl port-forward <pod_name> 8080:80

Delete a pod

kubectl delete pod <pod_name>

Deployment Management

List deployments

kubectl get deployments

Scale a deployment

kubectl scale deployment/<deployment_name> --replicas=3

Update deployment image

kubectl set image deployment/<deployment_name> <container_name>=nginx:latest

Roll back a deployment

kubectl rollout undo deployment/<deployment_name>

View rollout status

kubectl rollout status deployment/<deployment_name>

Namespace & Context

List namespaces

kubectl get namespaces

Change current namespace

kubectl config set-context --current --namespace=<namespace>

List contexts

kubectl config get-contexts

Switch context

kubectl config use-context <context_name>

Advanced & Troubleshooting

Apply changes to all resources in a directory

kubectl apply -f ./

Get resources by label selector

kubectl get <resource_type> -l <label_selector>

Explain a resource type

kubectl explain <resource_type>

View events in a namespace

kubectl get events -n <namespace>

View resource YAML/JSON output

kubectl get <resource_type> <resource_name> -o yaml