# kubectl — Control Kubernetes Clusters from the Command Line

> Practical guide to kubectl — manage pods, deployments, services and clusters, read logs, steer rollouts and debug, with examples for every command.

Source: https://www.jpkc.com/db/en/cheatsheets/containers/kubectl/

<!-- PROSE:intro -->
kubectl is the primary command-line tool for Kubernetes: every command talks to the cluster's API server through your kubeconfig and manages pods, deployments, services and every other resource. Which cluster you target is set by the active context, so you can switch between development and production with a single command. This guide walks you through the commands you reach for daily: viewing and applying resources, steering rollouts, reading logs and debugging inside a running pod.
<!-- PROSE:intro:end -->

## Cluster & Context

`kubectl cluster-info` — Display cluster endpoint information.

```bash
kubectl cluster-info
```

`kubectl config get-contexts` — List all available contexts (clusters).

```bash
kubectl config get-contexts
```

`kubectl config current-context` — Show the currently active context.

```bash
kubectl config current-context
```

`kubectl config use-context <name>` — Switch to a different context (cluster).

```bash
kubectl config use-context production
```

`kubectl config set-context --current --namespace=<ns>` — Set the default namespace for the current context.

```bash
kubectl config set-context --current --namespace=my-app
```

`kubectl version` — Show the client and server version.

```bash
kubectl version -o yaml
```

`kubectl api-resources` — List all available resource types and their short names.

```bash
kubectl api-resources
```

## Viewing Resources

`kubectl get <resource>` — List resources of a given type in the current namespace.

```bash
kubectl get pods
```

`kubectl get <resource> -A` — List resources across all namespaces.

```bash
kubectl get pods -A
```

`kubectl get <resource> -n <namespace>` — List resources in a specific namespace.

```bash
kubectl get pods -n production
```

`kubectl get <resource> -o wide` — Show additional details like node and IP.

```bash
kubectl get pods -o wide
```

`kubectl get <resource> -o yaml` — Output the resource definition as YAML.

```bash
kubectl get deployment nginx -o yaml
```

`kubectl get <resource> -o json` — Output the resource definition as JSON.

```bash
kubectl get pod my-pod -o json
```

`kubectl get all` — List all common resources (pods, services, deployments, etc.).

```bash
kubectl get all -n my-app
```

`kubectl describe <resource> <name>` — Show detailed information about a specific resource including events.

```bash
kubectl describe pod my-pod
```

`kubectl get <resource> -l <label>=<value>` — Filter resources by label selector.

```bash
kubectl get pods -l app=nginx
```

`kubectl get <resource> --sort-by=<field>` — Sort output by a specific field.

```bash
kubectl get pods --sort-by=.metadata.creationTimestamp
```

## Creating & Applying

`kubectl apply -f <file>` — Create or update resources defined in a YAML/JSON file.

```bash
kubectl apply -f deployment.yaml
```

`kubectl apply -f <directory>` — Apply all resource files in a directory.

```bash
kubectl apply -f ./k8s/
```

`kubectl apply -f <url>` — Apply a resource from a remote URL.

```bash
kubectl apply -f https://raw.githubusercontent.com/org/repo/main/deploy.yaml
```

`kubectl create deployment <name> --image=<image>` — Create a deployment imperatively.

```bash
kubectl create deployment nginx --image=nginx:alpine
```

`kubectl create namespace <name>` — Create a new namespace.

```bash
kubectl create namespace staging
```

`kubectl run <name> --image=<image>` — Create and run a pod.

```bash
kubectl run debug --image=busybox --rm -it -- sh
```

`kubectl expose deployment <name> --port=<port> --type=<type>` — Create a service for a deployment.

```bash
kubectl expose deployment nginx --port=80 --type=LoadBalancer
```

## Editing & Updating

`kubectl edit <resource> <name>` — Edit a resource in your default editor.

```bash
kubectl edit deployment nginx
```

`kubectl set image deployment/<name> <container>=<image>` — Update the image of a container in a deployment.

```bash
kubectl set image deployment/nginx nginx=nginx:1.25
```

`kubectl scale deployment <name> --replicas=<n>` — Scale a deployment to n replicas.

```bash
kubectl scale deployment nginx --replicas=5
```

`kubectl rollout status deployment/<name>` — Watch the rollout status of a deployment.

```bash
kubectl rollout status deployment/nginx
```

`kubectl rollout history deployment/<name>` — View the rollout history (revisions) of a deployment.

```bash
kubectl rollout history deployment/nginx
```

`kubectl rollout undo deployment/<name>` — Rollback a deployment to the previous revision.

```bash
kubectl rollout undo deployment/nginx
```

`kubectl rollout undo deployment/<name> --to-revision=<n>` — Rollback to a specific revision number.

```bash
kubectl rollout undo deployment/nginx --to-revision=3
```

`kubectl label <resource> <name> <key>=<value>` — Add or update a label on a resource.

```bash
kubectl label pod my-pod env=production
```

`kubectl annotate <resource> <name> <key>=<value>` — Add or update an annotation on a resource.

```bash
kubectl annotate deployment nginx description='Web server'
```

`kubectl patch <resource> <name> -p '<json>'` — Update specific fields of a resource using a JSON patch.

```bash
kubectl patch deployment nginx -p '{"spec":{"replicas":3}}'
```

## Deleting Resources

`kubectl delete <resource> <name>` — Delete a specific resource by name.

```bash
kubectl delete pod my-pod
```

`kubectl delete -f <file>` — Delete all resources defined in a file.

```bash
kubectl delete -f deployment.yaml
```

`kubectl delete <resource> -l <label>=<value>` — Delete all resources matching a label selector.

```bash
kubectl delete pods -l app=old-version
```

`kubectl delete namespace <name>` — Delete a namespace and all resources within it.

```bash
kubectl delete namespace staging
```

`kubectl delete pod <name> --grace-period=0 --force` — Force delete a stuck pod immediately.

```bash
kubectl delete pod stuck-pod --grace-period=0 --force
```

## Logs & Debugging

`kubectl logs <pod>` — Print the logs of a pod.

```bash
kubectl logs my-pod
```

`kubectl logs -f <pod>` — Stream (follow) the logs of a pod in real time.

```bash
kubectl logs -f my-pod
```

`kubectl logs <pod> -c <container>` — Print logs from a specific container in a multi-container pod.

```bash
kubectl logs my-pod -c sidecar
```

`kubectl logs <pod> --previous` — Print logs from the previous instance of a container (after a crash).

```bash
kubectl logs my-pod --previous
```

`kubectl logs -l <label>=<value>` — Print logs from all pods matching a label.

```bash
kubectl logs -l app=nginx --all-containers
```

`kubectl logs <pod> --tail=<n>` — Show only the last n lines of logs.

```bash
kubectl logs my-pod --tail=50
```

`kubectl logs <pod> --since=<duration>` — Show logs from the last duration (e.g., 1h, 30m).

```bash
kubectl logs my-pod --since=1h
```

`kubectl exec -it <pod> -- <command>` — Execute an interactive command in a running pod.

```bash
kubectl exec -it my-pod -- /bin/bash
```

`kubectl exec <pod> -- <command>` — Execute a non-interactive command in a pod.

```bash
kubectl exec my-pod -- cat /etc/config.yaml
```

`kubectl top pods` — Show CPU and memory usage for pods (requires metrics-server).

```bash
kubectl top pods -n my-app
```

`kubectl top nodes` — Show CPU and memory usage for nodes.

```bash
kubectl top nodes
```

`kubectl get events --sort-by=.lastTimestamp` — View cluster events sorted by time (useful for debugging).

```bash
kubectl get events --sort-by=.lastTimestamp -n my-app
```

## Port Forwarding & Proxy

`kubectl port-forward <pod> <local>:<remote>` — Forward a local port to a port on a pod.

```bash
kubectl port-forward my-pod 8080:80
```

`kubectl port-forward svc/<service> <local>:<remote>` — Forward a local port to a service.

```bash
kubectl port-forward svc/my-service 3000:80
```

`kubectl proxy` — Start a proxy to the Kubernetes API server on localhost:8001.

```bash
kubectl proxy
```

## Copying Files

`kubectl cp <pod>:<path> <local_path>` — Copy a file from a pod to the local filesystem.

```bash
kubectl cp my-pod:/var/log/app.log ./app.log
```

`kubectl cp <local_path> <pod>:<path>` — Copy a local file into a pod.

```bash
kubectl cp ./config.yaml my-pod:/app/config.yaml
```

`kubectl cp <ns>/<pod>:<path> <local_path>` — Copy from a pod in a specific namespace.

```bash
kubectl cp production/my-pod:/data/export.csv ./export.csv
```

## Secrets & ConfigMaps

`kubectl create secret generic <name> --from-literal=<key>=<value>` — Create a secret from literal key-value pairs.

```bash
kubectl create secret generic db-creds --from-literal=username=admin --from-literal=password=s3cret
```

`kubectl create secret generic <name> --from-file=<path>` — Create a secret from a file.

```bash
kubectl create secret generic tls-cert --from-file=cert.pem --from-file=key.pem
```

`kubectl get secret <name> -o jsonpath='{.data.<key>}' | base64 -d` — Decode and display a secret value.

```bash
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d
```

`kubectl create configmap <name> --from-literal=<key>=<value>` — Create a ConfigMap from literal key-value pairs.

```bash
kubectl create configmap app-config --from-literal=APP_ENV=production
```

`kubectl create configmap <name> --from-file=<path>` — Create a ConfigMap from a file or directory.

```bash
kubectl create configmap nginx-conf --from-file=nginx.conf
```

<!-- PROSE:outro -->
## Conclusion

kubectl is the hub of day-to-day cluster work: from a quick `get` to a targeted `rollout undo`, you handle almost any task without a dashboard. If you use it regularly, set up an alias (`k` for `kubectl`), shell completion and `--dry-run=client -o yaml` for clean GitOps – turning single commands into a reproducible workflow.

## Further Reading

- [kubectl – official reference](https://kubernetes.io/docs/reference/kubectl/) – every command and option in detail
- [kubectl Quick Reference](https://kubernetes.io/docs/reference/kubectl/quick-reference/) – compact command overview
- [Kubernetes – Wikipedia](https://en.wikipedia.org/wiki/Kubernetes) – background and architecture
<!-- PROSE:outro:end -->

## Related Commands

- [ddev](https://www.jpkc.com/db/en/cheatsheets/containers/ddev/) – local PHP development environments with Docker
- [docker](https://www.jpkc.com/db/en/cheatsheets/containers/docker/) – build and run individual containers
- [docker-compose](https://www.jpkc.com/db/en/cheatsheets/containers/docker-compose/) – orchestrate multi-container apps locally

