{"id":150,"date":"2022-10-19T17:57:07","date_gmt":"2022-10-19T17:57:07","guid":{"rendered":"https:\/\/merserver.com\/?p=150"},"modified":"2022-10-19T17:57:07","modified_gmt":"2022-10-19T17:57:07","slug":"kubectl-cheat-sheet","status":"publish","type":"post","link":"http:\/\/merserver.com\/index.php\/2022\/10\/19\/kubectl-cheat-sheet\/","title":{"rendered":"kubectl Cheat Sheet"},"content":{"rendered":"\n<p>This page contains a list of commonly used&nbsp;<code>kubectl<\/code>&nbsp;commands and flags.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"kubectl-autocomplete\">Kubectl autocomplete<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#kubectl-autocomplete\"><\/a><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"bash\">BASH<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#bash\"><\/a><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>source &lt;(kubectl completion bash) <em># setup autocomplete in bash into the current shell, bash-completion package should be installed first.<\/em>\necho \"source &lt;(kubectl completion bash)\" &gt;&gt; ~\/.bashrc <em># add autocomplete permanently to your bash shell.<\/em>\n<\/code><\/pre>\n\n\n\n<p>You can also use a shorthand alias for&nbsp;<code>kubectl<\/code>&nbsp;that also works with completion:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>alias k=kubectl\ncomplete -o default -F __start_kubectl k\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"zsh\">ZSH<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#zsh\"><\/a><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>source &lt;(kubectl completion zsh)  <em># setup autocomplete in zsh into the current shell<\/em>\necho '&#91;&#91; $commands&#91;kubectl] ]] &amp;&amp; source &lt;(kubectl completion zsh)' &gt;&gt; ~\/.zshrc <em># add autocomplete permanently to your zsh shell<\/em>\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"a-note-on-all-namespaces\">A Note on &#8211;all-namespaces<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#a-note-on-all-namespaces\"><\/a><\/h3>\n\n\n\n<p>Appending&nbsp;<code>--all-namespaces<\/code>&nbsp;happens frequently enough where you should be aware of the shorthand for&nbsp;<code>--all-namespaces<\/code>:<\/p>\n\n\n\n<p><code>kubectl -A<\/code><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"kubectl-context-and-configuration\">Kubectl context and configuration<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#kubectl-context-and-configuration\"><\/a><\/h2>\n\n\n\n<p>Set which Kubernetes cluster&nbsp;<code>kubectl<\/code>&nbsp;communicates with and modifies configuration information. See&nbsp;<a href=\"https:\/\/kubernetes.io\/docs\/tasks\/access-application-cluster\/configure-access-multiple-clusters\/\">Authenticating Across Clusters with kubeconfig<\/a>&nbsp;documentation for detailed config file information.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl config view <em># Show Merged kubeconfig settings.<\/em>\n\n<em># use multiple kubeconfig files at the same time and view merged config<\/em>\nKUBECONFIG=~\/.kube\/config:~\/.kube\/kubconfig2\n\nkubectl config view\n\n<em># get the password for the e2e user<\/em>\nkubectl config view -o jsonpath='{.users&#91;?(@.name == \"e2e\")].user.password}'\n\nkubectl config view -o jsonpath='{.users&#91;].name}'    <em># display the first user<\/em>\nkubectl config view -o jsonpath='{.users&#91;*].name}'   <em># get a list of users<\/em>\nkubectl config get-contexts                          <em># display list of contexts<\/em>\nkubectl config current-context                       <em># display the current-context<\/em>\nkubectl config use-context my-cluster-name           <em># set the default context to my-cluster-name<\/em>\n\nkubectl config set-cluster my-cluster-name           <em># set a cluster entry in the kubeconfig<\/em>\n\n<em># configure the URL to a proxy server to use for requests made by this client in the kubeconfig<\/em>\nkubectl config set-cluster my-cluster-name --proxy-url=my-proxy-url\n\n<em># add a new user to your kubeconf that supports basic auth<\/em>\nkubectl config set-credentials kubeuser\/foo.kubernetes.com --username=kubeuser --password=kubepassword\n\n<em># permanently save the namespace for all subsequent kubectl commands in that context.<\/em>\nkubectl config set-context --current --namespace=ggckad-s2\n\n<em># set a context utilizing a specific username and namespace.<\/em>\nkubectl config set-context gce --user=cluster-admin --namespace=foo <strong>\\\n<\/strong><strong><\/strong>  &amp;&amp; kubectl config use-context gce\n\nkubectl config unset users.foo                       <em># delete user foo<\/em>\n\n<em># short alias to set\/show context\/namespace (only works for bash and bash-compatible shells, current context to be set before using kn to set namespace) <\/em>\nalias kx='f() { &#91; \"$1\" ] &amp;&amp; kubectl config use-context $1 || kubectl config current-context ; } ; f'\nalias kn='f() { &#91; \"$1\" ] &amp;&amp; kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d\" \" -f6 ; } ; f'\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"kubectl-apply\">Kubectl apply<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#kubectl-apply\"><\/a><\/h2>\n\n\n\n<p><code>apply<\/code>&nbsp;manages applications through files defining Kubernetes resources. It creates and updates resources in a cluster through running&nbsp;<code>kubectl apply<\/code>. This is the recommended way of managing Kubernetes applications on production. See&nbsp;<a href=\"https:\/\/kubectl.docs.kubernetes.io\/\">Kubectl Book<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"creating-objects\">Creating objects<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#creating-objects\"><\/a><\/h2>\n\n\n\n<p>Kubernetes manifests can be defined in YAML or JSON. The file extension&nbsp;<code>.yaml<\/code>,&nbsp;<code>.yml<\/code>, and&nbsp;<code>.json<\/code>&nbsp;can be used.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl apply -f .\/my-manifest.yaml            <em># create resource(s)<\/em>\nkubectl apply -f .\/my1.yaml -f .\/my2.yaml      <em># create from multiple files<\/em>\nkubectl apply -f .\/dir                         <em># create resource(s) in all manifest files in dir<\/em>\nkubectl apply -f https:\/\/git.io\/vPieo          <em># create resource(s) from url<\/em>\nkubectl create deployment nginx --image=nginx  <em># start a single instance of nginx<\/em>\n\n<em># create a Job which prints \"Hello World\"<\/em>\nkubectl create job hello --image=busybox:1.28 -- echo \"Hello World\"\n\n<em># create a CronJob that prints \"Hello World\" every minute<\/em>\nkubectl create cronjob hello --image=busybox:1.28   --schedule=\"*\/1 * * * *\" -- echo \"Hello World\"\n\nkubectl explain pods                           <em># get the documentation for pod manifests<\/em>\n\n<em># Create multiple YAML objects from stdin<\/em>\ncat &lt;&lt;EOF | kubectl apply -f -\napiVersion: v1\nkind: Pod\nmetadata:\n  name: busybox-sleep\nspec:\n  containers:\n  - name: busybox\n    image: busybox:1.28\n    args:\n    - sleep\n    - \"1000000\"\n---\napiVersion: v1\nkind: Pod\nmetadata:\n  name: busybox-sleep-less\nspec:\n  containers:\n  - name: busybox\n    image: busybox:1.28\n    args:\n    - sleep\n    - \"1000\"\nEOF\n\n<em># Create a secret with several keys<\/em>\ncat &lt;&lt;EOF | kubectl apply -f -\napiVersion: v1\nkind: Secret\nmetadata:\n  name: mysecret\ntype: Opaque\ndata:\n  password: $(echo -n \"s33msi4\" | base64 -w0)\n  username: $(echo -n \"jane\" | base64 -w0)\nEOF\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"viewing-finding-resources\">Viewing, finding resources<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#viewing-finding-resources\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code><em># Get commands with basic output<\/em>\nkubectl get services                          <em># List all services in the namespace<\/em>\nkubectl get pods --all-namespaces             <em># List all pods in all namespaces<\/em>\nkubectl get pods -o wide                      <em># List all pods in the current namespace, with more details<\/em>\nkubectl get deployment my-dep                 <em># List a particular deployment<\/em>\nkubectl get pods                              <em># List all pods in the namespace<\/em>\nkubectl get pod my-pod -o yaml                <em># Get a pod's YAML<\/em>\n\n<em># Describe commands with verbose output<\/em>\nkubectl describe nodes my-node\nkubectl describe pods my-pod\n\n<em># List Services Sorted by Name<\/em>\nkubectl get services --sort-by=.metadata.name\n\n<em># List pods Sorted by Restart Count<\/em>\nkubectl get pods --sort-by='.status.containerStatuses&#91;0].restartCount'\n\n<em># List PersistentVolumes sorted by capacity<\/em>\nkubectl get pv --sort-by=.spec.capacity.storage\n\n<em># Get the version label of all pods with label app=cassandra<\/em>\nkubectl get pods --selector=app=cassandra -o <strong>\\\n<\/strong><strong><\/strong>  jsonpath='{.items&#91;*].metadata.labels.version}'\n\n<em># Retrieve the value of a key with dots, e.g. 'ca.crt'<\/em>\nkubectl get configmap myconfig <strong>\\\n<\/strong><strong><\/strong>  -o jsonpath='{.data.ca\\.crt}'\n\n<em># Retrieve a base64 encoded value with dashes instead of underscores.<\/em>\nkubectl get secret my-secret --template='{{index .data \"key-name-with-dashes\"}}'\n\n<em># Get all worker nodes (use a selector to exclude results that have a label<\/em>\n<em># named 'node-role.kubernetes.io\/control-plane')<\/em>\nkubectl get node --selector='!node-role.kubernetes.io\/control-plane'\n\n<em># Get all running pods in the namespace<\/em>\nkubectl get pods --field-selector=status.phase=Running\n\n<em># Get ExternalIPs of all nodes<\/em>\nkubectl get nodes -o jsonpath='{.items&#91;*].status.addresses&#91;?(@.type==\"ExternalIP\")].address}'\n\n<em># List Names of Pods that belong to Particular RC<\/em>\n<em># \"jq\" command useful for transformations that are too complex for jsonpath, it can be found at https:\/\/stedolan.github.io\/jq\/<\/em>\nsel=<strong>${<\/strong><strong>$(<\/strong>kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .&#91;] | \"\\(.key)=\\(.value),\"'<strong>)<\/strong>%?<strong>}<\/strong>\necho <strong>$(<\/strong>kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name}<strong>)<\/strong>\n\n<em># Show labels for all pods (or any other Kubernetes object that supports labelling)<\/em>\nkubectl get pods --show-labels\n\n<em># Check which nodes are ready<\/em>\nJSONPATH='{range .items&#91;*]}{@.metadata.name}:{range @.status.conditions&#91;*]}{@.type}={@.status};{end}{end}' <strong>\\\n<\/strong><strong><\/strong> &amp;&amp; kubectl get nodes -o jsonpath=\"$JSONPATH\" | grep \"Ready=True\"\n\n<em># Output decoded secrets without external tools<\/em>\nkubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{\"### \"}}{{$k}}{{\"\\n\"}}{{$v|base64decode}}{{\"\\n\\n\"}}{{end}}'\n\n<em># List all Secrets currently in use by a pod<\/em>\nkubectl get pods -o json | jq '.items&#91;].spec.containers&#91;].env&#91;]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq\n\n<em># List all containerIDs of initContainer of all pods<\/em>\n<em># Helpful when cleaning up stopped containers, while avoiding removal of initContainers.<\/em>\nkubectl get pods --all-namespaces -o jsonpath='{range .items&#91;*].status.initContainerStatuses&#91;*]}{.containerID}{\"\\n\"}{end}' | cut -d\/ -f3\n\n<em># List Events sorted by timestamp<\/em>\nkubectl get events --sort-by=.metadata.creationTimestamp\n\n<em># Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied.<\/em>\nkubectl diff -f .\/my-manifest.yaml\n\n<em># Produce a period-delimited tree of all keys returned for nodes<\/em>\n<em># Helpful when locating a key within a complex nested JSON structure<\/em>\nkubectl get nodes -o json | jq -c 'paths|join(\".\")'\n\n<em># Produce a period-delimited tree of all keys returned for pods, etc<\/em>\nkubectl get pods -o json | jq -c 'paths|join(\".\")'\n\n<em># Produce ENV for all pods, assuming you have a default container for the pods, default namespace and the `env` command is supported.<\/em>\n<em># Helpful when running any supported command across all pods, not just `env`<\/em>\n<strong>for<\/strong> pod in <strong>$(<\/strong>kubectl get po --output=jsonpath={.items..metadata.name}<strong>)<\/strong>; <strong>do<\/strong> echo $pod &amp;&amp; kubectl exec -it $pod -- env; <strong>done<\/strong>\n\n<em># Get a deployment's status subresource<\/em>\nkubectl get deployment nginx-deployment --subresource=status\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"updating-resources\">Updating resources<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#updating-resources\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl set image deployment\/frontend www=image:v2               <em># Rolling update \"www\" containers of \"frontend\" deployment, updating the image<\/em>\nkubectl rollout history deployment\/frontend                      <em># Check the history of deployments including the revision<\/em>\nkubectl rollout undo deployment\/frontend                         <em># Rollback to the previous deployment<\/em>\nkubectl rollout undo deployment\/frontend --to-revision=2         <em># Rollback to a specific revision<\/em>\nkubectl rollout status -w deployment\/frontend                    <em># Watch rolling update status of \"frontend\" deployment until completion<\/em>\nkubectl rollout restart deployment\/frontend                      <em># Rolling restart of the \"frontend\" deployment<\/em>\n\n\ncat pod.json | kubectl replace -f -                              <em># Replace a pod based on the JSON passed into stdin<\/em>\n\n<em># Force replace, delete and then re-create the resource. Will cause a service outage.<\/em>\nkubectl replace --force -f .\/pod.json\n\n<em># Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000<\/em>\nkubectl expose rc nginx --port=80 --target-port=8000\n\n<em># Update a single-container pod's image version (tag) to v4<\/em>\nkubectl get pod mypod -o yaml | sed 's\/\\(image: myimage\\):.*$\/\\1:v4\/' | kubectl replace -f -\n\nkubectl label pods my-pod new-label=awesome                      <em># Add a Label<\/em>\nkubectl annotate pods my-pod icon-url=http:\/\/goo.gl\/XXBTWq       <em># Add an annotation<\/em>\nkubectl autoscale deployment foo --min=2 --max=10                <em># Auto scale a deployment \"foo\"<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"patching-resources\">Patching resources<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#patching-resources\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code><em># Partially update a node<\/em>\nkubectl patch node k8s-node-1 -p '{\"spec\":{\"unschedulable\":true}}'\n\n<em># Update a container's image; spec.containers&#91;*].name is required because it's a merge key<\/em>\nkubectl patch pod valid-pod -p '{\"spec\":{\"containers\":&#91;{\"name\":\"kubernetes-serve-hostname\",\"image\":\"new image\"}]}}'\n\n<em># Update a container's image using a json patch with positional arrays<\/em>\nkubectl patch pod valid-pod --type='json' -p='&#91;{\"op\": \"replace\", \"path\": \"\/spec\/containers\/0\/image\", \"value\":\"new image\"}]'\n\n<em># Disable a deployment livenessProbe using a json patch with positional arrays<\/em>\nkubectl patch deployment valid-deployment  --type json   -p='&#91;{\"op\": \"remove\", \"path\": \"\/spec\/template\/spec\/containers\/0\/livenessProbe\"}]'\n\n<em># Add a new element to a positional array<\/em>\nkubectl patch sa default --type='json' -p='&#91;{\"op\": \"add\", \"path\": \"\/secrets\/1\", \"value\": {\"name\": \"whatever\" } }]'\n\n<em># Update a deployment's replica count by patching its scale subresource<\/em>\nkubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{\"spec\":{\"replicas\":2}}'\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"editing-resources\">Editing resources<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#editing-resources\"><\/a><\/h2>\n\n\n\n<p>Edit any API resource in your preferred editor.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl edit svc\/docker-registry                      <em># Edit the service named docker-registry<\/em>\nKUBE_EDITOR=\"nano\" kubectl edit svc\/docker-registry   <em># Use an alternative editor<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"scaling-resources\">Scaling resources<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#scaling-resources\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl scale --replicas=3 rs\/foo                                 <em># Scale a replicaset named 'foo' to 3<\/em>\nkubectl scale --replicas=3 -f foo.yaml                            <em># Scale a resource specified in \"foo.yaml\" to 3<\/em>\nkubectl scale --current-replicas=2 --replicas=3 deployment\/mysql  <em># If the deployment named mysql's current size is 2, scale mysql to 3<\/em>\nkubectl scale --replicas=5 rc\/foo rc\/bar rc\/baz                   <em># Scale multiple replication controllers<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"deleting-resources\">Deleting resources<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#deleting-resources\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl delete -f .\/pod.json                                      <em># Delete a pod using the type and name specified in pod.json<\/em>\nkubectl delete pod unwanted --now                                 <em># Delete a pod with no grace period<\/em>\nkubectl delete pod,service baz foo                                <em># Delete pods and services with same names \"baz\" and \"foo\"<\/em>\nkubectl delete pods,services -l name=myLabel                      <em># Delete pods and services with label name=myLabel<\/em>\nkubectl -n my-ns delete pod,svc --all                             <em># Delete all pods and services in namespace my-ns,<\/em>\n<em># Delete all pods matching the awk pattern1 or pattern2<\/em>\nkubectl get pods  -n mynamespace --no-headers=true | awk '\/pattern1|pattern2\/{print $1}' | xargs  kubectl delete -n mynamespace pod\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"interacting-with-running-pods\">Interacting with running Pods<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#interacting-with-running-pods\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl logs my-pod                                 <em># dump pod logs (stdout)<\/em>\nkubectl logs -l name=myLabel                        <em># dump pod logs, with label name=myLabel (stdout)<\/em>\nkubectl logs my-pod --previous                      <em># dump pod logs (stdout) for a previous instantiation of a container<\/em>\nkubectl logs my-pod -c my-container                 <em># dump pod container logs (stdout, multi-container case)<\/em>\nkubectl logs -l name=myLabel -c my-container        <em># dump pod logs, with label name=myLabel (stdout)<\/em>\nkubectl logs my-pod -c my-container --previous      <em># dump pod container logs (stdout, multi-container case) for a previous instantiation of a container<\/em>\nkubectl logs -f my-pod                              <em># stream pod logs (stdout)<\/em>\nkubectl logs -f my-pod -c my-container              <em># stream pod container logs (stdout, multi-container case)<\/em>\nkubectl logs -f -l name=myLabel --all-containers    <em># stream all pods logs with label name=myLabel (stdout)<\/em>\nkubectl run -i --tty busybox --image=busybox:1.28 -- sh  <em># Run pod as interactive shell<\/em>\nkubectl run nginx --image=nginx -n mynamespace      <em># Start a single instance of nginx pod in the namespace of mynamespace<\/em>\nkubectl run nginx --image=nginx                     <em># Run pod nginx and write its spec into a file called pod.yaml<\/em>\n--dry-run=client -o yaml &gt; pod.yaml\n\nkubectl attach my-pod -i                            <em># Attach to Running Container<\/em>\nkubectl port-forward my-pod 5000:6000               <em># Listen on port 5000 on the local machine and forward to port 6000 on my-pod<\/em>\nkubectl exec my-pod -- ls \/                         <em># Run command in existing pod (1 container case)<\/em>\nkubectl exec --stdin --tty my-pod -- \/bin\/sh        <em># Interactive shell access to a running pod (1 container case)<\/em>\nkubectl exec my-pod -c my-container -- ls \/         <em># Run command in existing pod (multi-container case)<\/em>\nkubectl top pod POD_NAME --containers               <em># Show metrics for a given pod and its containers<\/em>\nkubectl top pod POD_NAME --sort-by=cpu              <em># Show metrics for a given pod and sort it by 'cpu' or 'memory'<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"copy-files-and-directories-to-and-from-containers\">Copy files and directories to and from containers<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#copy-files-and-directories-to-and-from-containers\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl cp \/tmp\/foo_dir my-pod:\/tmp\/bar_dir            <em># Copy \/tmp\/foo_dir local directory to \/tmp\/bar_dir in a remote pod in the current namespace<\/em>\nkubectl cp \/tmp\/foo my-pod:\/tmp\/bar -c my-container    <em># Copy \/tmp\/foo local file to \/tmp\/bar in a remote pod in a specific container<\/em>\nkubectl cp \/tmp\/foo my-namespace\/my-pod:\/tmp\/bar       <em># Copy \/tmp\/foo local file to \/tmp\/bar in a remote pod in namespace my-namespace<\/em>\nkubectl cp my-namespace\/my-pod:\/tmp\/foo \/tmp\/bar       <em># Copy \/tmp\/foo from a remote pod to \/tmp\/bar locally<\/em>\n<\/code><\/pre>\n\n\n\n<p><strong>Note:<\/strong>&nbsp;<code>kubectl cp<\/code>&nbsp;requires that the &#8216;tar&#8217; binary is present in your container image. If &#8216;tar&#8217; is not present,<code>kubectl cp<\/code>&nbsp;will fail. For advanced use cases, such as symlinks, wildcard expansion or file mode preservation consider using&nbsp;<code>kubectl exec<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>tar cf - \/tmp\/foo | kubectl exec -i -n my-namespace my-pod -- tar xf - -C \/tmp\/bar           <em># Copy \/tmp\/foo local file to \/tmp\/bar in a remote pod in namespace my-namespace<\/em>\nkubectl exec -n my-namespace my-pod -- tar cf - \/tmp\/foo | tar xf - -C \/tmp\/bar    <em># Copy \/tmp\/foo from a remote pod to \/tmp\/bar locally<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"interacting-with-deployments-and-services\">Interacting with Deployments and Services<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#interacting-with-deployments-and-services\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl logs deploy\/my-deployment                         <em># dump Pod logs for a Deployment (single-container case)<\/em>\nkubectl logs deploy\/my-deployment -c my-container         <em># dump Pod logs for a Deployment (multi-container case)<\/em>\n\nkubectl port-forward svc\/my-service 5000                  <em># listen on local port 5000 and forward to port 5000 on Service backend<\/em>\nkubectl port-forward svc\/my-service 5000:my-service-port  <em># listen on local port 5000 and forward to Service target port with name &lt;my-service-port&gt;<\/em>\n\nkubectl port-forward deploy\/my-deployment 5000:6000       <em># listen on local port 5000 and forward to port 6000 on a Pod created by &lt;my-deployment&gt;<\/em>\nkubectl exec deploy\/my-deployment -- ls                   <em># run command in first Pod and first container in Deployment (single- or multi-container cases)<\/em>\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"interacting-with-nodes-and-cluster\">Interacting with Nodes and cluster<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#interacting-with-nodes-and-cluster\"><\/a><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl cordon my-node                                                <em># Mark my-node as unschedulable<\/em>\nkubectl drain my-node                                                 <em># Drain my-node in preparation for maintenance<\/em>\nkubectl uncordon my-node                                              <em># Mark my-node as schedulable<\/em>\nkubectl top node my-node                                              <em># Show metrics for a given node<\/em>\nkubectl cluster-info                                                  <em># Display addresses of the master and services<\/em>\nkubectl cluster-info dump                                             <em># Dump current cluster state to stdout<\/em>\nkubectl cluster-info dump --output-directory=\/path\/to\/cluster-state   <em># Dump current cluster state to \/path\/to\/cluster-state<\/em>\n\n<em># View existing taints on which exist on current nodes.<\/em>\nkubectl get nodes -o=custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints&#91;*].key,TaintValue:.spec.taints&#91;*].value,TaintEffect:.spec.taints&#91;*].effect\n\n<em># If a taint with that key and effect already exists, its value is replaced as specified.<\/em>\nkubectl taint nodes foo dedicated=special-user:NoSchedule\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"resource-types\">Resource types<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#resource-types\"><\/a><\/h3>\n\n\n\n<p>List all supported resource types along with their shortnames,&nbsp;<a href=\"https:\/\/kubernetes.io\/docs\/concepts\/overview\/kubernetes-api\/#api-groups-and-versioning\">API group<\/a>, whether they are&nbsp;<a href=\"https:\/\/kubernetes.io\/docs\/concepts\/overview\/working-with-objects\/namespaces\">namespaced<\/a>, and&nbsp;<a href=\"https:\/\/kubernetes.io\/docs\/concepts\/overview\/working-with-objects\/kubernetes-objects\">Kind<\/a>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl api-resources\n<\/code><\/pre>\n\n\n\n<p>Other operations for exploring API resources:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>kubectl api-resources --namespaced=true      <em># All namespaced resources<\/em>\nkubectl api-resources --namespaced=false     <em># All non-namespaced resources<\/em>\nkubectl api-resources -o name                <em># All resources with simple output (only the resource name)<\/em>\nkubectl api-resources -o wide                <em># All resources with expanded (aka \"wide\") output<\/em>\nkubectl api-resources --verbs=list,get       <em># All resources that support the \"list\" and \"get\" request verbs<\/em>\nkubectl api-resources --api-group=extensions <em># All resources in the \"extensions\" API group<\/em>\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"formatting-output\">Formatting output<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#formatting-output\"><\/a><\/h3>\n\n\n\n<p>To output details to your terminal window in a specific format, add the&nbsp;<code>-o<\/code>&nbsp;(or&nbsp;<code>--output<\/code>) flag to a supported&nbsp;<code>kubectl<\/code>&nbsp;command.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Output format<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>-o=custom-columns=&lt;spec&gt;<\/code><\/td><td>Print a table using a comma separated list of custom columns<\/td><\/tr><tr><td><code>-o=custom-columns-file=&lt;filename&gt;<\/code><\/td><td>Print a table using the custom columns template in the&nbsp;<code>&lt;filename&gt;<\/code>&nbsp;file<\/td><\/tr><tr><td><code>-o=json<\/code><\/td><td>Output a JSON formatted API object<\/td><\/tr><tr><td><code>-o=jsonpath=&lt;template&gt;<\/code><\/td><td>Print the fields defined in a&nbsp;<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/jsonpath\">jsonpath<\/a>&nbsp;expression<\/td><\/tr><tr><td><code>-o=jsonpath-file=&lt;filename&gt;<\/code><\/td><td>Print the fields defined by the&nbsp;<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/jsonpath\">jsonpath<\/a>&nbsp;expression in the&nbsp;<code>&lt;filename&gt;<\/code>&nbsp;file<\/td><\/tr><tr><td><code>-o=name<\/code><\/td><td>Print only the resource name and nothing else<\/td><\/tr><tr><td><code>-o=wide<\/code><\/td><td>Output in the plain-text format with any additional information, and for pods, the node name is included<\/td><\/tr><tr><td><code>-o=yaml<\/code><\/td><td>Output a YAML formatted API object<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Examples using&nbsp;<code>-o=custom-columns<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><em># All images running in a cluster<\/em>\nkubectl get pods -A -o=custom-columns='DATA:spec.containers&#91;*].image'\n\n<em># All images running in namespace: default, grouped by Pod<\/em>\nkubectl get pods --namespace default --output=custom-columns=\"NAME:.metadata.name,IMAGE:.spec.containers&#91;*].image\"\n\n <em># All images excluding \"registry.k8s.io\/coredns:1.6.2\"<\/em>\nkubectl get pods -A -o=custom-columns='DATA:spec.containers&#91;?(@.image!=\"registry.k8s.io\/coredns:1.6.2\")].image'\n\n<em># All fields under metadata regardless of name<\/em>\nkubectl get pods -A -o=custom-columns='DATA:metadata.*'\n<\/code><\/pre>\n\n\n\n<p>More examples in the kubectl&nbsp;<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/#custom-columns\">reference documentation<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"kubectl-output-verbosity-and-debugging\">Kubectl output verbosity and debugging<a href=\"https:\/\/kubernetes.io\/docs\/reference\/kubectl\/cheatsheet\/#kubectl-output-verbosity-and-debugging\"><\/a><\/h3>\n\n\n\n<p>Kubectl verbosity is controlled with the&nbsp;<code>-v<\/code>&nbsp;or&nbsp;<code>--v<\/code>&nbsp;flags followed by an integer representing the log level. General Kubernetes logging conventions and the associated log levels are described&nbsp;<a href=\"https:\/\/github.com\/kubernetes\/community\/blob\/master\/contributors\/devel\/sig-instrumentation\/logging.md\">here<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Verbosity<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>--v=0<\/code><\/td><td>Generally useful for this to&nbsp;<em>always<\/em>&nbsp;be visible to a cluster operator.<\/td><\/tr><tr><td><code>--v=1<\/code><\/td><td>A reasonable default log level if you don&#8217;t want verbosity.<\/td><\/tr><tr><td><code>--v=2<\/code><\/td><td>Useful steady state information about the service and important log messages that may correlate to significant changes in the system. This is the recommended default log level for most systems.<\/td><\/tr><tr><td><code>--v=3<\/code><\/td><td>Extended information about changes.<\/td><\/tr><tr><td><code>--v=4<\/code><\/td><td>Debug level verbosity.<\/td><\/tr><tr><td><code>--v=5<\/code><\/td><td>Trace level verbosity.<\/td><\/tr><tr><td><code>--v=6<\/code><\/td><td>Display requested resources.<\/td><\/tr><tr><td><code>--v=7<\/code><\/td><td>Display HTTP request headers.<\/td><\/tr><tr><td><code>--v=8<\/code><\/td><td>Display HTTP request contents.<\/td><\/tr><tr><td><code>--v=9<\/code><\/td><td>Display HTTP request contents without truncation of contents.<\/td><\/tr><\/tbody><\/table><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>This page contains a list of commonly used&nbsp;kubectl&nbsp;commands and flags. Kubectl autocomplete BASH You can also use a shorthand alias for&nbsp;kubectl&nbsp;that also works with completion: ZSH A Note on &#8211;all-namespaces Appending&nbsp;&#8211;all-namespaces&nbsp;happens frequently enough where you should be aware of the shorthand for&nbsp;&#8211;all-namespaces: kubectl -A Kubectl context and configuration Set which Kubernetes cluster&nbsp;kubectl&nbsp;communicates with and modifies&#8230;<\/p>\n<p class=\"more-link-wrap\"><a href=\"http:\/\/merserver.com\/index.php\/2022\/10\/19\/kubectl-cheat-sheet\/\" class=\"more-link\">Read More<span class=\"screen-reader-text\"> &ldquo;kubectl Cheat Sheet&rdquo;<\/span> &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6,5],"tags":[],"class_list":["post-150","post","type-post","status-publish","format-standard","hentry","category-it","category-kubernetes"],"_links":{"self":[{"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/posts\/150","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/comments?post=150"}],"version-history":[{"count":1,"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/posts\/150\/revisions"}],"predecessor-version":[{"id":151,"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/posts\/150\/revisions\/151"}],"wp:attachment":[{"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/media?parent=150"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/categories?post=150"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/merserver.com\/index.php\/wp-json\/wp\/v2\/tags?post=150"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}