Kubernetes Kubernetes cheat sheet

Kubernetesis one of the most famous container orchestration platforms. An open-source platform, Kubernetes automates a wide range of management, deployment, and scaling tasks for containerized applications. A Kubernetes cluster is a set of control panes and worker machines called nodes, which form a cluster every time you deploy Kubernetes. If you want to command your Kubernetes cluster to perform tasks, you can use the command line kubectl. It uses Kubernetes API to communicate with a Kubernetes cluster’s control pane. With it, you can perform almost any action on your Kubernetes cluster without needing to make direct API calls. Programmers with Kubernetes knowledge are in great demand, as many companies and organizations embrace Kubernetes to develop applications efficiently. Ready to make the most out of Kubernetes commands with kubectl? We’ve put together this kubectl cheat sheet filled with insights about managing Kubernetes clusters, kubectl logs, kubectl list pods, and much more. With this kubectl and Kubernetes commands cheat sheet, you’ll be equipped to tackle any application project. Here is a link to the kubectl cheat sheet that you can download and access offline whenever and wherever needed. Please follow this link if you're interested in a Kubernetes Benchmarking Study.

Dashboard Kubernetes preset

Kubernetes vs Docker

KubernetesDocker swarm
Setup is very complicated, but once installed, cluster is robust
For Kubernetes, GUI is the Kubernetes Dashboard
Highly scalable and scales fast
Kubernetes can do auto-scaling
Manual intervention needed for load balancing traffic between different containers and pods
Kubernetes can deploy rolling updates and does automatic rollbacks
Kubernetes can share storage volumes only with the other containers in the same pod
Kubernetes has In-built tools for logging and monitoring
Kubernetes can do auto-scaling
Kubernetes can deploy rolling updates and does automatic rollbacks
Kubernetes can share storage volumes only with the other containers in the same pod
Has In-built tools for logging and monitoring
Docker Swarm's Installation is very simple, but the cluster is not robust
There is no GUI
Highly scalable and scales 5x faster than Kubernetes
Cannot do auto-scaling
Docker swarm does auto load balancing of traffic between containers in the cluster
Can deploy rolling updates, but not automatic rollback
Can share storage volumes with any other container
Uses 3rd party tools like ELK stack should be used for logging and monitoring
Docker swarm does auto load balancing of traffic between containers in the cluster
Can deploy rolling updates, but not automatic rollback
Can share storage volumes with any the other containers

Containers vs VM

containers vs VM

Kubernetes tools stack wheel

Kubernetes Tools Stack Wheel

Kubectl Autocomplete

BASH

To set upan autocomplete in bash within the current shell, you must install the bash-completion package using the following command.

source <(kubectl completion bash)

For adding the autocomplete permanently to your bash shell, run the following command.

echo "source <(kubectl completion bash)" >> ~/.bashrc

You can use a short name for Kubectl, as shown below.

alias k=kubectl
        complete -F __start_kubectl k

ZSH

To set upan autocomplete in zsh within the current shell, you need to run the following command.

source <(kubectl completion zsh)

You can also run the following command to make it permanent.

echo "[[ $commands[kubectl] ]] && source <(kubectl completion zsh)" >> ~/.zshrc

Kubectl Context and Configuration

The next set of commands will cover display, context, and user information.

Display merged kubeconfig settings with this command:

kubectl config view

Use several kubeconfig files simultaneously and view the merged config with this command:

KUBECONFIG=~/.kube/config:~/.kube/kubconfig2
        kubectl config view​
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'

Get the password of the e2e user with this command:

Run this command to display the first user:

kubectl config view -o jsonpath='{.users[].name}'

Display the entire list of the users with this command:

kubectl config view -o jsonpath='{.users[*].name}'

Display the list of context:

kubectl config get-contexts

Display the current context:

kubectl config current-context

Set the default context to the my-cluster-name:

kubectl config use-context my-cluster-name

Add a new user to your kubeconf supporting basic authentication:

kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword

Save the namespace permanently for all subsequent kubectl commands in that context:

kubectl config set-context --current --namespace=ggckad-s2

Set a context with a specific username and namespace:

kubectl config set-context gce --user=cluster-admin --namespace=foo \
         && kubectl config use-context gce​
kubectl config unset users.foo

Delete the user named foo:

Set or show context/namespace with a short alias:

alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
        alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'

The “apply” helps manage the applications through files that define Kubernetes resources. You can easily create and update resources within the cluster by running kubectl apply. It is one of the commonly practiced ways for managing applications on production. Kubectl Apply

Creating Objects

Objects in Kubernetes are persistent entities that represent the state of your cluster.

Specifically, they can describe:

  • Containerized applications running (and on which nodes)
  • Available resources to those applications
  • Policies about application behavior, like upgrades and restart policies

A Kubernetes object is a "record of intent." After you create the object, the Kubernetes system will constantly work to ensure that the object exists. By creating an object, you'retelling the Kubernetes system about how your cluster's workload will look (desired state).

If you want to work with Kubernetes objects (create, modify, or delete), you need to use the Kubernetes API. The kubectl command-line interface (CLI) makes it easier for you to make the necessary Kubernetes API calls. Interested in using the Kubernetes API directly? Try out one of the client libraries.

You can define the Kubernetes manifest file in YAML or JSON. This manifest file comes with the extension as .yaml, .yml, and .json, etc.

The following are the commands that allow you to work around the manifest file. “Apply” is used to push the required changes based on your configuration files.

Create resources:

kubectl apply -f ./my-manifest.yaml  

Create from multiple files:

kubectl apply -f ./my1.yaml -f ./my2.yaml

Create resources in all manifest files in dir:

kubectl apply -f ./dir

** the “create” command will help in generating the new resources from files or standard input devices.

Create resources from url:

kubectl apply -f https://git.io/vPieo

Start a single instance of Nginx using the following command:

kubectl create deployment nginx --image=nginx

Create a job that will print "Hello World:"

kubectl create job hello --image=busybox:1.28 -- echo "Hello World"

Create a CronJob that will print "Hello World" every minute:

kubectl create cronjob hello --image=busybox:1.28   --schedule="*/1 * * * *" -- echo "Hello World"​
kubectl explain pods

Retrieve the documentation for pod manifests:

Create multiple YAML objects from stdin:

cat <<EOF | kubectl apply -f -
        apiVersion: v1
        kind: Pod
        metadata:
         name: busybox-sleep
        spec:
         containers:
         - name: busybox
           image: busybox:1.28
           args:
           - sleep
           - "1000000"
        ---
        apiVersion: v1
        kind: Pod
        metadata:
         name: busybox-sleep-less
        spec:
         containers:
         - name: busybox
           image: busybox:1.28
           args:
           - sleep
           - "1000"
        EOF
        
        Create a secret

with several keys:

cat <<EOF | kubectl apply -f -
        apiVersion: v1
        kind: Secret
        metadata:
         name: mysecret
        type: Opaque
        data:
         password: $(echo -n "s33msi4" | base64 -w0)
         username: $(echo -n "jane" | base64 -w0)
        EOF

Viewing and Finding Resources

In Kubernetes, we can define aresource as an endpoint present in the Kubernetes API. It is responsible for storing the collection of specific sorts of API objects. For example, the resource named built-in pods is a collection of pod objects.

We can use acustom resource to extend the Kubernetes API. It is not necessary that a custom resource should always be available in the default installation of Kubernetes. Moreover, custom resources have made it possible for us to create various core Kubernetes functions, which make Kubernetes more modular in nature.

Dynamic registration makes it possible for custom resources to appear or disappear in a running cluster. Also, cluster admins have the right to update custom resources without concerning the cluster itself. Like the built-in resources, users can also create and access the objects of custom resourceswhen they are installed.

“Get” Commands with Basic Outputs

These commands will help you fetch cluster data from various sources:

  • kubectl get services: # for displaying all services in the namespace
  • kubectl get pods --all-namespaces:# for displaying all pods in all namespaces
  • kubectl get pods -owide:# for displaying all pods in the current namespace, with more details
  • kubectl get deployment my-dep:# for displaying a particular deployment
  • kubectl get pods:# for displaying all pods in the namespace
  • kubectl get pod my-pod -o yaml:# to get a pod's YAML

“Describe” Commands to Display the Verbose Output

kubectl describe nodes my-node
        kubectl describe pods my-pod

List services sorted by name: Commands for Listing, Period Trees, and More

kubectl get services --sort-by=.metadata.name

List pods sorted by restart count:

kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'

List PersistentVolumes sorted by capacity:

kubectl get pv --sort-by=.spec.capacity.storage

Obtain theversion label of all pods with label app=cassandra:

kubectl get pods --selector=app=cassandra -o \
         jsonpath='{.items[*].metadata.labels.version}'

Get the value of a key with dots, e.g. 'ca.crt:'

kubectl get configmap myconfig \
         -o jsonpath='{.data.ca\.crt}'

For this command, use a selector for excluding the results that have a label # named 'node-role.kubernetes.io/master.'View all worker nodes:

kubectl get node --selector='!node-role.kubernetes.io/master'

Get all running pods in the namespace:

kubectl get pods --field-selector=status.phase=Running

Get the ExternalIPs of all nodes:

kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'

This command is useful for transformations that are too complex for jsonpath, and can be found here. List pod names of Pods that belong to Particular RC "jq:"

sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
        echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})​
kubectl get pods --show-labels

Show all pod labels:

Checkwhich nodes are ready:

JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
        && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"​
kubectl get secret my-secret -o go-template='{{range $k,$v := .data}}{{"### "}}{{$k}}{{"\n"}}{{$v|base64decode}}{{"\n\n"}}{{end}}'

List all secrets currently in use by a pod:Get theoutput decoded secrets without external tools:

kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq

This command is helpful when cleaning up stopped containers, while avoiding removal of initContainers.List all containerIDs of initContainer of all pods:

kubectl get pods --all-namespaces -o jsonpath='{range .items[*].status.initContainerStatuses[*]}{.containerID}{"\n"}{end}' | cut -d/ -f3​
kubectl get events --sort-by=.metadata.creationTimestamp

List events sorted by timestamp:

Compare current and future cluster states:

kubectl diff -f ./my-manifest.yaml

Create a period-delimited tree of all keys returned for nodes:

This command is helpful when locating a key within a complex nested JSON structure.

kubectl get nodes -o json | jq -c 'paths|join(".")'

Create a period-delimited tree of all keys returned for pods, etc.:

kubectl get pods -o json | jq -c 'paths|join(".")'

Create an ENV for all pods:

This command assumes you have a default container for the pods, default namespace and that the `env` command is supported. It is helpful when running any supported command across all pods, not just `env.`

for pod in $(kubectl get po --output=jsonpath={.items..metadata.name}); do echo $pod && kubectl exec -it $pod -- env; done

Updating Resources

  • Roll the update "www" containers of "frontend" deployment, updating the image:
kubectl set image deployment/frontend www=image:v2            
  • Check the history of deployments, including the revision:
kubectl rollout history deployment/frontend      
  • Rollback to the previous deployment:
kubectl rollout undo deployment/frontend
  • Rollback to a specific revision:
kubectl rollout undo deployment/frontend --to-revision=2  
  • Watch the rolling update status of "frontend" deployment until completion:
kubectl rollout status -w deployment/frontend  
  • Roll the restart of the "frontend" deployment:
kubectl rollout restart deployment/frontend                      
  • Force replace, delete and then re-create the resource:

This command may cause a service outage.

kubectl replace --force -f ./pod.json
  • Createa service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000:
kubectl expose rc nginx --port=80 --target-port=8000
  • Update a single-container pod's image version (tag) to v4:
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
  • Add a label:
kubectl label pods my-pod new-label=awesome  
  • Add an annotation:
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq
  • Autoscale a deployment named “foo:”
kubectl autoscale deployment foo --min=2 --max=10

Patching Resources

These commands will patch resources as required.

  • Partially update a node:
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
  • Updatea container's image:

Keep in mind that the spec.containers[*].name is required because it's a merge key

kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
  • Updatea container's image using a json patch with positional arrays:
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'
  • DeploylivenessProbe using a json patch with positional arrays:
kubectl patch deployment valid-deployment  --type json   -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'
  • Adda new element to a positional array:
kubectl patch sa default --type='json' -p='[{"op": "add", "path": "/secrets/1", "value": {"name": "whatever" } }]'

Editing Resources

These commands will edit resources as required.

  • Edit the service named “docker-registry:”
kubectl edit svc/docker-registry  
  • Use an alternative editor:
KUBE_EDITOR="nano" kubectl edit svc/docker-registry

Scaling Resources

These commands will scale resources as required.

  • Scalereplicaset named 'foo' to 3:
kubectl scale --replicas=3 rs/foo  
  • Scalea resource specified in "foo.yaml" to 3:
kubectl scale --replicas=3 -f foo.yaml    
  • Scale mysql to 3 (when the deployment named mysql's current size is 2):
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
  • Scale multiple replication controllers:
kubectl scale --replicas=5 rc/foo rc/bar rc/baz                  

Deleting Resources

The following commands are used to delete the resources as required.

  • Delete a podusing the type and name specified in pod.json:
kubectl delete -f ./pod.json                                    
  • Delete apod with no grace period:
kubectl delete pod unwanted -now
  • Delete podsand services with the same names "baz" and "foo:"
kubectl delete pod, service baz foo  
  • Deletepods and services with label name=myLabel:
kubectl delete pods, services -l name=myLabel    
  • Delete all pods and services in namespace my-ns:
kubectl -n my-ns delete pod, svc --all      
  • Deleteall pods matching the awk pattern1 or pattern2:
kubectl get pods  -n mynamespace --no-headers=true | awk '/pattern1|pattern2/{print $1}' | xargs  kubectl delete -n mynamespace pod

Interacting with Running Pods

This next set of commands will show youhow to interact with running pods:

  • Dumppod logs (stdout):
kubectl logs my-pod      
  • Dumppod logs, with label name=myLabel (stdout):
kubectl logs -l name=myLabel            
  • Dumppod logs (stdout) for a previous instantiation of a container:
kubectl logs my-pod --previous            
  • Dumppod container logs (stdout, multi-container case):
kubectl logs my-pod -c my-container    
  • Dumppod logs, with label name=myLabel (stdout):
kubectl logs -l name=myLabel -c my-container    
  • Dumppod container logs (stdout, multi-container case) for a previous instantiation of a container:
kubectl logs my-pod -c my-container --previous    
  • Streampod logs (stdout):
kubectl logs -f my-pod              
  • Streampod container logs (stdout, multi-container case):
kubectl logs -f my-pod -c my-container    
  • Streamall pods logs with label name=myLabel (stdout):
kubectl logs -f -l name=myLabel --all-containers  
  • Run apod as interactive shell:
kubectl run -i --tty busybox --image=busybox:1.28 -- sh  
  • Starta single instance of nginx pod in the namespace of mynamespace:
kubectl run nginx --image=nginx -n mynamespace  
  • Run apod nginx and write its spec into a file called pod.yaml:
kubectl run nginx --image=nginx                    
        --dry-run=client -o yaml > pod.yaml

Attach pod to Running Container:

kubectl attach my-pod -i                            
  • Listenon port 5000 on the local machine and forward to port 6000 on my-pod:
kubectl port-forward my-pod 5000:6000              
  • Run acommand in existing pod (1 container case):
kubectl exec my-pod -- ls /                        
  • Access interactive shell to a running pod (1 container case)
kubectl exec --stdin --tty my-pod -- /bin/sh        
  • Run acommand in existing pod (multi-container case):
kubectl exec my-pod -c my-container -- ls /        
  • Displaymetrics for a given pod and its containers:
kubectl top pod POD_NAME --containers              
  • Showmetrics for a given pod and sort it by 'cpu' or 'memory:'
kubectl top pod POD_NAME --sort-by=cpu              

Copying Files and Directories

These commands help you copy files and directories:

  • Copythe /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the current namespace:
kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir            
  • Copythe /tmp/foo local file to /tmp/bar in a remote pod in a specific container:
kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container  
  • Copythe /tmp/foo local file to /tmp/bar in a remote pod in namespace my-namespace:
kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar      
  • Copy the /tmp/foo from a remote pod to /tmp/bar locally:
kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar      

Interacting with Deployments and Services

This next set of commands helps you interact (dump, listen, view, run) with deployments and services.

  • Dump pod logs for a deployment (single-container case):
kubectl logs deploy/my-deployment                        
  • Dump pod logs for a deployment (multi-container case):
kubectl logs deploy/my-deployment -c my-container        
  • Listenon local port 5000 and forward to port 5000 on Service backend
kubectl port-forward svc/my-service 5000                  
  • Listenon local port 5000 and forward to Service target port with name <my-service-port>:
kubectl port-forward svc/my-service 5000:my-service-port  
  • Listenon local port 5000 and forward to port 6000 on a Pod created by <my-deployment>:
kubectl port-forward deploy/my-deployment 5000:6000      
  • Runcommand in first pod and first container in deployment (single- or multi-container cases):
kubectl exec deploy/my-deployment -- ls                  

Interacting with Nodes and Cluster

Learn how to interact with nodes and clusters with this next set of commands.

  • Mark my-node as unschedulable:
kubectl cordon my-node                                                
  • Drain my-node to prepare for maintenance:
kubectl drain my-node                                                
  • Mark my-node as schedulable:
kubectl uncordon my-node                                              
  • Showmetrics for a given node:
kubectl top node my-node                                              
  • Displayaddresses of the master and services:
kubectl cluster-info                                                  
  • Dumpcurrent cluster state to stdout:
kubectl cluster-info dump                                            
  • Dumpcurrent cluster state to /path/to/cluster-state:
kubectl cluster-info dump --output-directory=/path/to/cluster-state  
  • Replace value as specified (if a taint with that key and effect already exists):
kubectl taint nodes foo dedicated=special-user:NoSchedule

Cluster Management

These commands help you manage clusters, from listing API resources to displaying pertinent information:

  • Displayendpoint information about the master and services in the cluster:
kubectl cluster-info
  • Display the Kubernetes version running on the client and server:
kubectl version
  • Retrieve the cluster configuration
kubectl config view
  • List available API resources:
kubectl api-resources
  • For listing the API versions that are available
kubectl api-versions
  • List everything:
kubectl get all --all-namespaces

DaemonSet

A DaemonSet makes sure that nodes run pod copies. Nodes and pods are added to clusters. Similarly, pods undergo garbage collection once nodes are removed.When you delete a DaemonSet, all the pods created by it also get deleted.

Some typical DaemonSet uses for every node:

  • running a cluster storage
  • running a logs collection
  • running a node monitoring

For simple cases, one DaemonSet could cover all nodes and each daemon type. A more complex setup might use multiple DaemonSets for a single type of daemon, but with different flags, memory, and CPU requests for various hardware types.

Shortcode = ds
  • Listone or more DaemonSets:
kubectl get daemonset​
  • Edit and update the definition of one or more DaemonSet:
kubectl edit daemonset <daemonset_name>
  • Delete a DaemonSet:
kubectl delete daemonset <daemonset_name>
  • Create a new DaemonSet:
kubectl create daemonset <daemonset_name>
  • Manage the rollout of a DaemonSet:
kubectl rollout daemonset
  • Show the detailed state of DaemonSets within a namespace:
kubectl describe ds <daemonset_name> -n <namespace_name>

Deployments

A deployment runs multiple application replicas and automatically replaces any failed or unresponsive instances.Deployments are managed by the Kubernetes Deployment Controller. Moreover, deployments make sure that user requests are served through one or more instances of your application.

Shortcode = deploy
  • List one or more deployments:
kubectl get deployment
  • Show the detailed state of one or more deployments:
kubectl describe deployment <deployment_name>
  • Edit and update the definition of one or more server deployment:
kubectl edit deployment <deployment_name>
  • Create a new deployment:
kubectl create deployment <deployment_name>
  • Delete the deployments:
kubectl delete deployment <deployment_name>
  • Check the rollout status of a deployment:
kubectl rollout status deployment <deployment_name>

Events

A Kubernetes event is an object in the framework automatically generated in response to changes with other resources—like nodes, pods, or containers.

State changes lie at the center of this. For example, phases across a pod’s lifecycle—like a transition from pending to running, or statuses like successful or failed—may trigger a Kubernetes event. The same goes for reallocations and scheduling.

Shortcode = ev
  • Listall recent events for all system resources:
kubectl get events
  • List all warnings only:
kubectl get events --field-selector type=Warning
  • List all events (excluding Pod events):
kubectl get events --field-selector involvedObject.kind!=Pod
  • Pull all events for a single node with a specific name:
kubectl get events --field-selector involvedObject.kind=Node, involvedObject.name=<node_name>
  • Filter out normal events from a list of events:
kubectl get events --field-selector type!=Normal

Components of Kubernetes

The Main Components of Kubernetes Explained.

Managing modern, distributed applications is challenging. Keeping systems reliable, scalable, and fault-tolerant requires sophisticated orchestration tools.

This is where Kubernetes comes in.

Kubernetes (K8s) streamlines the deployment, scaling, and management of containerized applications, making it a cornerstone of modern DevOps.

At its core, Kubernetes is built on a handful of key components, each with a distinct role.

By understanding them, you'll have a strong foundational understanding — Let's dive in!

Node: Machines (physical or virtual) that run containerized applications. Nodes host the workload, which is composed of Pods.
Pod: The smallest deployable unit in K8s, containing one or more containers that share storage, networking, and resources.
Control plane: The "brain" of the cluster that manages system state and oversees Nodes and Pods.

It consists of:

• API server: handles cluster management requests
• Scheduler: assigns Pods to Nodes
• Controller manager: maintains the desired state
• etcd: stores cluster configuration and state as a distributed key-value store

𝗦𝗲𝗿𝘃𝗶𝗰𝗲: Provides stable endpoints (IP/DNS) to enable communication between Pods or expose applications to external users.
𝗜𝗻𝗴𝗿𝗲𝘀𝘀: Manages external HTTP/HTTPS traffic, routing it to the appropriate services within the cluster.
𝗡𝗮𝗺𝗲𝘀𝗽𝗮𝗰𝗲: A virtual cluster within a Kubernetes cluster, allowing for resource isolation and multi-tenancy.
𝗣𝗲𝗿𝘀𝗶𝘀𝘁𝗲𝗻𝘁 𝘃𝗼𝗹𝘂𝗺𝗲: Decouples storage from Pods, enabling data persistence across container restarts or deletions.

The components above work together to form a powerful system for automating application orchestration. Kubernetes has become the go-to platform for ensuring reliability and scalability in modern software systems. That said it's not the answer for every application. There's a steep learning curve and complexity involved. Sometimes simpler/lightweight options like Docker Swarm or PaaS solutions are a better fit.

components of Kubernetes

Logs

System component logs record events happening in a cluster, which can be useful for debugging.To see the desired details of those events, you can configure log verbosity.

There can be two types of logs, namely fine-grained and coarse-grained. Coarse-grained logs represent errors within a component. On the other hand, fine-grained logs represent step-by-step traces of events.

  • Printthe logs for a pod:
kubectl logs <pod_name>
  • Print the logs for the last hour for a pod:
kubectl logs --since=1h <pod_name>
  • Retrieve the most recent 20 lines of logs:
kubectl logs --tail=20 <pod_name>
  • Retrieve the logs from a service and optionally selecting which container:
kubectl logs -f <service_name> [-c <$container>]
  • Print the logs for a pod and follow new logs:
kubectl logs -f <pod_name>
  • Print the logs for a container in a pod:
kubectl logs -c <container_name> <pod_name>
  • Get the output of the logs for a pod into a file named ‘pod.log:’
kubectl logs <pod_name> pod.log
  • Check the logs for a previously failed pod:
kubectl logs --previous <pod_name>

Namespaces

In Kubernetes, namespaces provide a mechanism for isolating groups of resources within a single cluster. Resource names must be uniquewithina namespace but notacrossnamespaces. Namespace-based scoping is applicable only for namespaced objects (e.g., Deployments, Services, etc.) and not for cluster-wide objects (e.g., StorageClass, Nodes, PersistentVolumes, etc.).

Shortcode = ns
  • Createa namespace <name>:
kubectl create namespace <namespace_name>
  • List one or more namespaces:
kubectl get namespace <namespace_name>
  • Display the detailed state of one or more namespace:
kubectl describe namespace <namespace_name>
  • Delete a namespace:
kubectl delete namespace <namespace_name>
  • Edit and update a namespace definition:
kubectl edit namespace <namespace_name>
  • Display the Resource (CPU/Memory/Storage) usage for a namespace:
kubectl top namespace <namespace_name>

Replication Controllers

A replication controller is a key Kubernetes feature, responsible for:

  • managing the pod lifecycle
  • ensuring the specified number of pod replicas are running at any point in time
  • Increases or decreases the specified number of pods
Shortcode = rc
  • Listall the replication controllers:
kubectl get rc
  • List the replication controllers by namespace:
kubectl get rc --namespace="<namespace_name>"

ReplicaSets

RepliceSets ensure you have a stable set of replica pods operating. You might use one to confirm that identical pods are available.

Shortcode = rs
  • Listall the ReplicaSets:
kubectl get replicasets
  • Show the detailed state of one or more ReplicaSets:
kubectl describe replicasets <replicaset_name>
  • Scale a ReplicaSet:
kubectl scale --replicas=[x]

Secrets

A secret is an object containing a small amount of sensitive data such as a password, token, or key. This information is either stored in a Pod specification or in a container image.Ifyou use a Secret, you don't need to include confidential data in your application code.

  • Create anew secret:
kubectl create secret
  • List all secrets:
kubectl get secrets
  • List all the required details about secrets:
kubectl describe secrets
  • Delete a secret:
kubectl delete secret <secret_name>

Services

Services are anabstract way to expose an application running on a set of Pods as a network service.

If you want to use any unfamiliar servicediscovery mechanism, there is no need to make changes to your application when developed using Kubernetes. This is because Kubernetes assigns each pod with a unique IP address and a single DNS can manage all the load across multiple pods.

Shortcode = svc
  • Listone or more services:
kubectl get services
  • Show the detailed state of service:
kubectl describe services
  • Expose a replication controller, service, deployment, or pod as a new Kubernetes service:
kubectl expose deployment [deployment_name]
  • Edit and update the definition of one or more services:
kubectl edit services

Service Accounts

A service account provides an identity for processes that run in a pod. Here is a useful introduction to Service Accounts.

Shortcode = sa
  • Listservice accounts:
kubectl get serviceaccounts
  • Show the detailed state of one or more service accounts:
kubectl describe serviceaccounts
  • Replace a service account:
kubectl replace serviceaccount
  • Delete a service account:
kubectl delete serviceaccount <service_account_name>

StatefulSet

StatefulSets represent a set of pods with unique, persistent identities and stable hostnames that GKE maintains regardless of where they are scheduled.The persistent disk storage associated with the StatefulSet is responsible for storing state information and other resilient data for the given StatefulSet pod.

Shortcode = sts
  • ListStatefulSet:
kubectl get statefulset
  • Delete StatefulSet only (not pods):
kubectl delete statefulset/[stateful_set_name] --cascade=false

Conclusion

If you want to enter the Kubernetes world with high proficiency in managing containers, this kubectl cheat sheet will help you achieve your goals. Don’t forget to download our kubectl cheat sheet so you can have easy access to the commands whenever you’d like. Good luck with your job interview.

Frequently Asked Questions

1. How Do I Get Pod Details in Kubernetes?

List all kubectl pods in the namespace

kubectl get pods

2. How Do You Use the kubectl Commands?

Here’s the basic syntax for kubectl:

kubectl [command] [TYPE] [NAME] [flags]

The commandportion describes what operation you want to perform, such as create, describe, get, apply, and delete.

  • create generates new resources from files or standard input devices
  • describe retrieves details about a resource or resource group
  • get fetches cluster data from various sources
  • delete erases resources as required
  • apply pushes changes based on your configuration files

Typedescribes the kind of resource kubectl is targeting, such as pods, services, daemonsets, deployments, replicasets, statefulsets, Kubernetes jobs, and cron jobs, etc

Nameis a case sensitive field that specifies the name of the resource in question. Flagshelp denote special options or requests made to a certain resource.

3. Can I Command in kubectl?

Yes, you can command in kubectl. You can query the API authorization layer using kubectl’s auth can-i subcommand. This command determines whether the user using kubectl currently can perform the given action or not using the SelfSubjectAccessReview API.

4. How Do I Get Pod Status With kubectl?

You can run the following command to get pod status:

kubectl get pods -n kube-system some-appdeployment -o jsonpath="Name: {.metadata.name} Status: {.status.phase}"

5. How Do I Run a kubectl Command in a Shell Script?

You can execute shell commands using one of the following methods:

Open a bash command shell in kubectl exec, where you can execute commands:

kubectl exec -it pod-name -- /bin/bash
  • Get a shell to the suitecrm-0 pod:
kubectl exec -it suitecrm-0 -- /bin/bash
  • Use kubectl exec to execute commands directly:
kubectl exec -it pod-name -- /bin/bash -c "command(s)"
  • List the root directory of the suitecrm-0 pod:
kubectl exec -it suitecrm-0 -- /bin/bash -c "ls /"

Cluster state metrics

DESCRIPTIONNAME IN KUBE-STATE-METRICSCOMMAND
Running podskube_pod_status_phasekubectl get pods
Number of pods desired for a Deploymentkube_deployment_spec_replicaskubectl get deployment <DEPLOYMENT>
Number of pods desired for a DaemonSetkube_daemonset_status_desired_number_scheduledkubectl get daemonset <DAEMONSET>
Number of pods currently running in a Deploymentkube_deployment_status_replicaskubectl get deployment <DEPLOYMENT>
Number of pods currently running in a DaemonSetkube_daemonset_status_current_number_scheduledkubectl get daemonset <DAEMONSET>
Number of pods currently available in a Deploymentkube_deployment_status_replicas_availablekubectl get deployment <DEPLOYMENT>
Number of pods currently available in a DaemonSetkube_daemonset_status_number_availablekubectl get daemonset <DAEMONSET>
Number of pods currently not available in a Deploymentkube_deployment_status_replicas_unavailablekubectl get deployment <DEPLOYMENT>
Number of pods currently not available in a DaemonSetkube_daemonset_status_number_unavailablekubectl get daemonset <DAEMONSET>

Node resource and status metrics
DESCRIPTIONNAME IN KUBE-STATE-METRICSCOMMAND
Current health status of a node (kubelet)kube_node_status_conditionkubectl describe node <NODE_NAME>
Total memory requests (bytes) per nodekube_pod_container_resource_requests_memory_byteskubectl describe node <NODE_NAME>
Total memory in use on a nodeN/Akubectl describe node <NODE_NAME>
Total CPU requests (cores) per nodekube_pod_container_resource_requests_cpu_coreskubectl describe node <NODE_NAME>
Total CPU in use on a nodeN/Akubectl describe node <NODE_NAME>

Job Metrics
DESCRIPTIONNAME IN KUBE-STATE-METRICSCOMMAND
Number of successful jobkube_job_status_succeededkubectl get jobs --all-namespaces | grep “succeedeed”
Number of failed jobskube_job_status_failedkubectl get jobs --all-namespaces | grep “failed”
Number of active jobskube_job_status_activekubectl get jobs --all-namespaces
Number of CronJobskube_cronjob_infokubectl get cronjobs --all-namespaces

Service Metrics
DESCRIPTIONNAME IN KUBE-STATE-METRICSCOMMAND
Service types per clusterkube_service_infokubectl get services --all-namespaces
Number of pods running by servicekubectl get pods --selector=<SERVICE_SELECTOR> -o=namekubectl get jobs --all-namespaces

Container Metrics
DESCRIPTIONNAME IN KUBE-STATE-METRICSCOMMAND
Containers running on a podkube_pod_container_infokubectl describe pod <POD_NAME>
Containers restarted on a podkube_pod_container_status_restarts_totalkubectl describe pod <POD_NAME>
Containers terminated on a podkube_pod_container_status_terminatedkubectl describe pod <POD_NAME>

Disk I/O & Network metrics
DESCRIPTIONNAME IN KUBE-STATE-METRICSCOMMAND
Network in per nodecontainer_network_receive_bytes_totalkubectl get --raw /api/v1/nodes/<NODE_NAME>/proxy/metrics/cadvisor
Network out per nodecontainer_network_transmit_bytes_totalkubectl get --raw /api/v1/nodes/<NODE_NAME>/proxy/metrics/cadvisor
Disk writes per nodecontainer_fs_writes_bytes_totalkubectl get --raw /api/v1/nodes/<NODE_NAME>/proxy/metrics/cadvisor
Disk reads per nodecontainer_fs_reads_bytes_totalkubectl get --raw /api/v1/nodes/<NODE_NAME>/proxy/metrics/cadvisor
Network errors per nodecontainer_network_receive_errors_total, container_network_transmit_errors_totalkubectl get --raw /api/v1/nodes/<NODE_NAME>/proxy/metrics/cadvisor

Kubernetes events
DESCRIPTIONNAME IN KUBE-STATE-METRICSCOMMAND
List events kubectl get events

Create & Deploy Kubernetes clusters

1- Create Kubernetes clusters

See how a fictional public relations firm uses Kubernetes capabilities to deploy a containerized app on IBM Cloud. With IBM Watson® Tone Analyzer Service, the firm gets feedback on its press releases.

Create Kubernetes clusters

2- Deploy a scalable web app

Learn how to scaffold a web app, run it locally in a container, then deploy it to an IBM Cloud Kubernetes cluster. Also learn how to bind a custom domain, monitor the health of the environment and scale.

Deploy a scalable web app

3- Analyze logs, monitor apps

Learn how to create a cluster and configure the log analysis and monitoring services. Then, deploy an app to the cluster, view and analyze logs with Kibana and view health and metrics with Grafana.

Analyze logs, monitor apps

4- Deploy apps continuously

Learn how to set up a CI/CD pipeline for containerized apps running in Kubernetes. This use case covers the setup of source control, build, test and deploy and integrating security scanners, analytics and more.

Deploy apps continuously

Kubernetes Patterns

Each pattern serves a specific purpose, and should be carefully chosen and applied for the best results.

  1. 𝗜𝗻𝗶𝘁 𝗖𝗼𝗻𝘁𝗮𝗶𝗻𝗲𝗿:
    A special container that runs before the main container in a pod, used to set up the environment for the main application.
  2. 𝗦𝗶𝗱𝗲𝗰𝗮𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻:
    A helper container added to the main application container, enhancing or adding functionality to the main container without changing it.
  3. 𝗔𝗺𝗯𝗮𝘀𝘀𝗮𝗱𝗼𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻:
    A proxy container that manages communication and connections for the main container, handling things like network tasks.
  4. 𝗔𝗱𝗮𝗽𝘁𝗲𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻:
    A container that standardizes and transforms the output of the main container to a format usable by other systems.
  5. 𝗖𝗼𝗻𝘁𝗿𝗼𝗹𝗹𝗲𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻:
    A loop in Kubernetes that continuously monitors and adjusts the state of objects to match the desired state.
  6. 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻:
    An advanced controller with domain-specific knowledge, used to automate complex tasks for an application, like upgrades and backups.

Kubernetes cluster interface

See the Pen Kubernetes cluster by Fabien Laurent Patrice Egot (@equant_org) on CodePen.