Kubernetes CLI (kubectl) tips you didn't know about
A collection of more than 20 useful and practical Kubernetes CLI tips from the Kubernetes community.
kubectl
:alias k=kubectl
kubectl
a lot, so why not make it shorter.1. Set up load-based horizontal pod autoscaling on your Kubernetes resources
kubectl autoscale deployment foo --min=2 --max=10
2. Create a new job from a cronjob
kubectl create job --from=cronjob/<name of cronjob> <name of this run>
3. Enumerate permissions for a given service account
kubectl -n <namespace> auth can-i --list --as system:serviceaccount:<namespace>:<service account name>
4. Annotate resources
# To add annotation
kubectl annotate <resource-type>/<resource-name> foo=bar
# To remove annotation
kubectl annotate <resource-type>/<resource-name> foo-
5. Get a list of endpoints across all namespaces
kubectl get ep -A
6. Get a list of events sorted by lastTimestamp
kubectl get events --sort-by=".lastTimestamp"
7. Watch all warnings across the namespaces
kubectl get events -w --field-selector=type=Warning -A
8. Add the EVENT
column to the list of watched pods
kubectl get pods --watch --output-watch-events
9. Get raw JSON for the various APIs
kubectl get --raw /apis/apps/v1
# Get metrics
kubectl get --raw /metrics
10. Wait for specific pods to be ready
kubectl wait --for=condition=ready pod -l foo=bar
11. Explain the various resources
kubectl explain pod.spec
12. Get all resources that match a selector
kubectl get deployments,replicasets,pods,services --selector=hello=yourecute
13. Forward a port from a service to a local port
kubectl port-forward svc/<service-name> <local-port>:<remote-port>
14. List the environment variables for a resource
kubectl set env <resource>/<resource-name> --list
15. Get a list of pods and the node they run on
kubectl get po -o=custom-columns=NODE:.spec.nodeName,NAME:.metadata.name
16. Create a starter YAML manifest for deployment (also works for other resources)
kubectl create deploy nginx-deployment --image=nginx --dry-run=client -o yaml
17. Get a list of pods sorted by memory usage
kubectl top pods -A --sort-by='memory'
18. Get a list of pods that have a specific label value set
kubectl get pods -l 'app in (foo,bar)'
19. Get the pod logs before the last restart
kubectl logs <pod-name> --previous
20. Copy a file from a pod to a local file
kubectl cp <namespace>/<pod>:<file_path> <local_file_path>
21. Delete a pod immediately
kubectl delete pod <pod-name> --now
22. Show the logs from pods with specific labels
kubectl logs -l app=xyz
23. Get more information about the resources (aka wide-view)
kubectl get <resource> -o wide
24. Output and apply the patch
# Edit a resource and get the patch
kubectl edit <resource>/<name> --output-patch
# Use the output from the command above to apply the patch
kubectl patch --patch=<output_from_previous_command>