kubectl
DevOps,  Kubernetes

(My) kubectl cheatsheet

Table of Contents


General purpose

# Lists all configured contexts
kubectl config get-contexts
 
# Changes the default namespace
kubectl config set-context --current --namespace=namespace_name
 
# Elects a node as worker
kubectl label node node_name node-role.kubernetes.io/worker=worker
 
# Removes taint from node, the "-" at end of node role means "untaint" rather than "taint"
kubectl taint node node_name node-role.kubernetes.io/control-plane-

Fetching objects info

# lists all pods on default namespace showing only their name
Kubectl get pods -o=name
 
# lists all pods on default namespace showing a custom list of attributes and setting columns names
k get pods -o=custom-columns="NAME:.metadata.name,STATUS:.status.phase"

Executing pods

# Creates and outputs to the console (as YAML) the code to create a pod running image-nginx
kubectl run --image=nginx --dry-run=client -o yaml mypod
 
# Gives you access to the shell (bash) of container container_name running into pod pod_name
kubectl exec -it [container_name] pod_name -- bash
 
# Creates and runs a pod with container image = nginx
kubectl run --image=nginx mypod

Networking

# forwards requests from port 16686 (node) to port 16686 (cluster) accepting requests from all network interfaces (param --address 0.0.0.0
kubectl port-forward --address 0.0.0.0  $(kubectl get pods -l=app="jaeger" -o name) 16686:16686

Accessing pod logs

# stream logs from pod pod_name on namespace ns
kubectl logs -f -n ns pods/pod_name
 
# stream logs from pod pod_name on namespace ns newer than a relative duration
kubectl logs --since=1h -n ns pods/pod_name
 
# return logs after a specific date (pod=pod_name, namespace=ns)
kubectl logs --since-time=2020-08-13T10:46:00.000000000Z -n ns pods/pod_name
 
# print the logs for the previous instance of the container (pod=pod_name, namespace=ns)
kubectl logs --previous -n ns pods/pod_name
 
# print the logs of this container (pod=pod_name, namespace=ns)
kubectl logs -c -n ns pods/pod_name
 
# print all events in chronological order (pod=pod_name, namespace=ns)
kubectl get events --sort-by=’.metadata.creationTimestamp’ -n ns pods/pod_name
 
# print pod details like status or recent events (pod=pod_name, namespace=ns)
kubectl describe pod -n ns pods/pod_name
 
# multi-container pod, selects logs from a specific container (pod=pod_name, namespace=ns)
kubectl logs -c container_name pod_name -n ns pods/pod_name