kubectlcheatsheet.com
Open in
urlscan Pro
188.114.97.3
Public Scan
Submitted URL: http://kubectlcheatsheet.com/
Effective URL: https://kubectlcheatsheet.com/
Submission: On June 25 via api from CH — Scanned from NL
Effective URL: https://kubectlcheatsheet.com/
Submission: On June 25 via api from CH — Scanned from NL
Form analysis
0 forms found in the DOMText Content
Toggle navigation * Home * Submit Cheats * Tmux * Docker KUBECTL CHEAT SHEET & QUICK REFERENCE * facebook * twitter * reddit * linkedin * tumblr * Whatsapp * QRCode SCAN TO ACCESS CONTEXT AND CONFIGURATION $ kubectl config view View the current kubeconfig file $ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}' Get the password for the e2e user $ kubectl config view -o jsonpath='{.users[].name}' Display the first user in the kubeconfig $ kubectl config view -o jsonpath='{.users[*].name}' Get a list of users in the kubeconfig $ kubectl config get-contexts Display the list of contexts in the kubeconfig $ kubectl config current-context Display the current context in the kubeconfig $ kubectl config use-context my-cluster-name Set the default context to my-cluster-name $ kubectl config set-cluster my-cluster-name Set a cluster entry in the kubeconfig $ kubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url Configure the URL to a proxy server in the kubeconfig $ kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword Add a new user to the kubeconfig with basic auth $ kubectl config set-context --current --namespace=ggckad-s2 Permanently save the namespace for all subsequent kubectl commands $ kubectl config set-context gce --user=cluster-admin --namespace=foo && kubectl config use-context gce Set a context with a specific username and namespace $ kubectl config unset users.foo Delete user foo from the kubeconfig COPYING FILES AND DIRECTORIES $ kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the current namespace $ kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container $ kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace my-namespace $ kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar Copy /tmp/foo from a remote pod to /tmp/bar locally $ tar cf - /tmp/foo | kubectl exec -i -n my-namespace my-pod -- tar xf - -C /tmp/bar Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace my-namespace $ kubectl exec -n my-namespace my-pod -- tar cf - /tmp/foo | tar xf - -C /tmp/bar Copy /tmp/foo from a remote pod to /tmp/bar locally CREATING OBJECTS $ kubectl apply -f ./my-manifest.yaml Create resource(s) $ kubectl apply -f ./my1.yaml -f ./my2.yaml Create from multiple files $ kubectl apply -f ./dir Create resource(s) in all manifest files in dir $ kubectl apply -f https://example.com/manifest.yaml Create resource(s) from url (Note: this is an example domain and does not contain a valid manifest) $ kubectl create -f my-pod.yaml Create a new pod $ kubectl create namespace my-namespace Create a new namespace named my-namespace $ kubectl create deployment nginx --image=nginx Start a single instance of nginx $ kubectl create job hello --image=busybox:1.28 -- echo 'Hello World' Create a Job which prints 'Hello World' $ kubectl create cronjob hello --image=busybox:1.28 --schedule='*/1 * * * *' -- echo 'Hello World' Create a CronJob that prints 'Hello World' every minute $ kubectl explain pods Get the documentation for pod manifests DELETING RESOURCES $ kubectl delete -f ./pod.json Delete a pod using the type and name specified in pod.json $ kubectl delete pod my-pod Delete a pod $ kubectl delete pod unwanted --now Delete a pod with no grace period $ kubectl delete pod,service baz foo Delete pods and services with same names "baz" and "foo" $ kubectl delete pods,services -l name=myLabel Delete pods and services with label name=myLabel $ kubectl -n my-ns delete pod,svc --all Delete all pods and services in namespace my-ns $ kubectl get pods -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs kubectl delete -n mynamespace pod Delete all pods matching the awk pattern1 or pattern2 EDITING RESOURCES $ kubectl edit svc/docker-registry Edit the service named docker-registry $ KUBE_EDITOR="nano" kubectl edit svc/docker-registry Use an alternative editor to edit the service named docker-registry INTERACTING WITH DEPLOYMENTS AND SERVICES $ kubectl logs deploy/my-deployment Dump Pod logs for a Deployment (single-container case) $ kubectl logs deploy/my-deployment -c my-container Dump Pod logs for a Deployment (multi-container case) $ kubectl port-forward svc/my-service 5000 Listen on local port 5000 and forward to port 5000 on Service backend $ kubectl port-forward svc/my-service 5000:my-service-port Listen on local port 5000 and forward to Service target port with name $ kubectl port-forward deploy/my-deployment 5000:6000 Listen on local port 5000 and forward to port 6000 on a Pod created by $ kubectl exec deploy/my-deployment -- ls Run command in first Pod and first container in Deployment (single- or multi-container cases) INTERACTING WITH NODES AND CLUSTER $ kubectl cordon my-node Mark my-node as unschedulable $ kubectl drain my-node Drain my-node in preparation for maintenance $ kubectl uncordon my-node Mark my-node as schedulable $ kubectl top node my-node Show metrics for a given node $ kubectl cluster-info Display addresses of the master and services $ kubectl cluster-info dump Dump current cluster state to stdout $ kubectl cluster-info dump --output-directory=/path/to/cluster-state Dump current cluster state to /path/to/cluster-state $ kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect' View existing taints on which exist on current nodes. $ kubectl taint nodes foo dedicated=special-user:NoSchedule If a taint with that key and effect already exists, its value is replaced as specified. INTERACTING WITH RUNNING PODS $ kubectl logs my-pod Dump pod logs (stdout) $ kubectl logs -l name=myLabel Dump pod logs, with label name=myLabel (stdout) $ kubectl logs my-pod --previous Dump pod logs (stdout) for a previous instantiation of a container $ kubectl logs my-pod -c my-container Dump pod container logs (stdout, multi-container case) $ kubectl logs -l name=myLabel -c my-container Dump pod container logs, with label name=myLabel (stdout) $ kubectl logs my-pod -c my-container --previous Dump pod container logs (stdout, multi-container case) for a previous instantiation of a container $ kubectl logs -f my-pod Stream pod logs (stdout) $ kubectl logs -f my-pod -c my-container Stream pod container logs (stdout, multi-container case) $ kubectl logs -f -l name=myLabel --all-containers Stream all pods logs with label name=myLabel (stdout) $ kubectl run -i --tty busybox --image=busybox:1.28 -- sh Run pod as interactive shell $ kubectl run nginx --image=nginx -n mynamespace Start a single instance of nginx pod in the namespace of mynamespace $ kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml Generate spec for running pod nginx and write it into a file called pod.yaml $ kubectl attach my-pod -i Attach to Running Container $ kubectl port-forward my-pod 5000:6000 Listen on port 5000 on the local machine and forward to port 6000 on my-pod $ kubectl exec my-pod -- ls / Run command in existing pod (1 container case) $ kubectl exec --stdin --tty my-pod -- /bin/sh Interactive shell access to a running pod (1 container case) $ kubectl exec my-pod -c my-container -- ls / Run command in existing pod (multi-container case) $ kubectl top pod POD_NAME --containers Show metrics for a given pod and its containers $ kubectl top pod POD_NAME --sort-by=cpu Show metrics for a given pod and sort it by 'cpu' or 'memory' PATCHING RESOURCES $ kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}' Partially update a node $ kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}' Update a container's image; spec.containers[*].name is required because it's a merge key $ kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]' Update a container's image using a json patch with positional arrays $ kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]' Disable a deployment livenessProbe using a json patch with positional arrays $ kubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]' Add a new element to a positional array $ kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}' Update a deployment's replica count by patching its scale subresource RESOURCE TYPES $ kubectl api-resources List all available resources in the cluster $ kubectl api-resources --namespaced=true List all namespaced resources $ kubectl api-resources --namespaced=false List all non-namespaced resources $ kubectl api-resources -o name List all resources with simple output (only the resource name) $ kubectl api-resources -o wide List all resources with expanded (aka 'wide') output $ kubectl api-resources --verbs=list,get List all resources that support the 'list' and 'get' request verbs $ kubectl api-resources --api-group=extensions List all resources in the 'extensions' API group SCALING RESOURCES $ kubectl scale --replicas=3 rs/foo Scale a replicaset named 'foo' to 3 $ kubectl scale --replicas=3 -f foo.yaml Scale a resource specified in "foo.yaml" to 3 $ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql If the deployment named mysql's current size is 2, scale mysql to 3 $ kubectl scale --replicas=5 rc/foo rc/bar rc/baz Scale multiple replication controllers UPDATING RESOURCES $ kubectl set image deployment/frontend www=image:v2 Rolling update "www" containers of "frontend" deployment, updating the image $ kubectl rollout history deployment/frontend Check the history of deployments including the revision $ kubectl rollout undo deployment/frontend Rollback to the previous deployment $ kubectl rollout undo deployment/frontend --to-revision=2 Rollback to a specific revision $ kubectl rollout status -w deployment/frontend Watch rolling update status of "frontend" deployment until completion $ kubectl rollout restart deployment/frontend Rolling restart of the "frontend" deployment $ cat pod.json | kubectl replace -f - Replace a pod based on the JSON passed into stdin $ kubectl replace --force -f ./pod.json Force replace, delete and then re-create the resource. Will cause a service outage. $ kubectl expose rc nginx --port=80 --target-port=8000 Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000 $ kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f - Update a single-container pod's image version (tag) to v4 $ kubectl label pods my-pod new-label=awesome Add a Label $ kubectl label pods my-pod new-label- Remove a label $ kubectl label pods my-pod new-label=new-value --overwrite Overwrite an existing value $ kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq Add an annotation $ kubectl annotate pods my-pod icon-url- Remove annotation $ kubectl autoscale deployment foo --min=2 --max=10 Auto scale a deployment "foo" VIEWING AND FINDING RESOURCES $ kubectl get services List all services in the namespace $ kubectl get pods --all-namespaces List all pods in all namespaces $ kubectl get namespaces List all namespaces $ kubectl get pods -o wide List all pods in the current namespace, with more details $ kubectl get deployment my-dep List a particular deployment $ kubectl get pods List all pods in the namespace $ kubectl get pod my-pod -o yaml Get a pod's YAML $ kubectl describe nodes my-node Describe nodes with verbose output $ kubectl describe pods my-pod Describe pods with verbose output $ kubectl get services --sort-by=.metadata.name List Services Sorted by Name $ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' List pods Sorted by Restart Count $ kubectl get pv --sort-by=.spec.capacity.storage List PersistentVolumes sorted by capacity $ kubectl get pods --selector=app=cassandra -o jsonpath='{.items[*].metadata.labels.version}' Get the version label of all pods with label app=cassandra $ kubectl get configmap myconfig -o jsonpath='{.data.ca\.crt}' Retrieve the value of a key with dots, e.g. 'ca.crt' $ kubectl get secret my-secret --template='{{index .data "key-name-with-dashes"}}' Retrieve a base64 encoded value with dashes instead of underscores. $ kubectl get node --selector='!node-role.kubernetes.io/control-plane' Get all worker nodes (use a selector to exclude results that have a label named 'node-role.kubernetes.io/control-plane') $ kubectl get pods --field-selector=status.phase=Running Get all running pods in the namespace $ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}' Get ExternalIPs of all nodes $ kubectl get pods --show-labels Show labels for all pods (or any other Kubernetes object that supports labelling) $ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True" Check which nodes are ready $ kubectl get node -o custom-columns='NODE_NAME:.metadata.name,STATUS:.status.conditions[?(@.type=="Ready")].status' Check which nodes are ready with custom-columns $ kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{" "}}{{$v|base64decode}}{{" "}}{{end}}' Output decoded secrets without external tools $ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq List all Secrets currently in use by a pod $ kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{" "}{end}' | cut -d/ -f3 List all containerIDs of initContainer of all pods $ kubectl get events --sort-by=.metadata.creationTimestamp List Events sorted by timestamp $ kubectl events --types=Warning List all warning events $ kubectl diff -f ./my-manifest.yaml Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied. $ kubectl get nodes -o json | jq -c 'paths|join(".")' Produce a period-delimited tree of all keys returned for nodes $ kubectl get pods -o json | jq -c 'paths|join(".")' Produce a period-delimited tree of all keys returned for pods, etc $ for pod in $(kubectl get po --output=jsonpath={.items..metadata.name}); do echo $pod && kubectl exec -it $pod -- env; done Produce ENV for all pods, assuming you have a default container for the pods, default namespace and the `env` command is supported $ kubectl get deployment nginx-deployment --subresource=status Get a deployment's status subresource