kubectl Cheat Sheet: The Basics and 5 Little Known Operations
Published: 2023-04-17 14:36:32

[Image Source](https://www.vecteezy.com/photo/5241319-businessman-working-with-a-cloud-computing-diagram-on-the-new-computer-interface)

## What Is kubectl?
kubectl is a command-line tool used for deploying and managing applications on a Kubernetes cluster. It is an essential tool for interacting with a cluster, allowing users to inspect, create, update, and delete resources in the cluster. With kubectl, you can manage the state of your applications, inspect logs, and troubleshoot issues. It provides a simple, human-readable interface for interacting with the Kubernetes API, allowing you to perform a wide range of operations, from deploying new applications to scaling existing ones.

kubectl is designed to be highly extensible and customizable, with a wide range of plugins and extensions available to add additional functionality. It also supports a variety of output formats, including JSON, YAML, and human-readable text, making it easy to integrate with other tools and automation systems. kubectl is an essential component in the toolchain of a [cloud operations professional](https://spot.io/cloudops/).

The Kubernetes API is a RESTful API, and kubectl sends HTTP requests to the API to perform various operations on the cluster. For example, you can use kubectl to create, read, update, and delete resources in the cluster, such as pods, services, and deployments. These operations are performed by sending HTTP requests to the appropriate endpoint in the Kubernetes API, such as the /api/v1/pods endpoint for managing pods.

### kubectl Concepts

The basic concepts of kubectl include resources, commands, and flags.

A resource in Kubernetes is a representation of a specific object in the cluster, such as a pod, service, or deployment. Each resource has a type attribute that specifies the type of object it represents, and a name field that provides a unique identifier for the object.

kubectl commands are structured as follows: `kubectl <command> <type> <name> [flags]`. The command specifies the action you want to perform, such as create, get, delete, or update. The type attribute specifies the type of resource you want to manage, such as a pod, service, or deployment. The name field provides the name of the specific resource you want to manage. Finally, flags are used to provide additional options and modify the behavior of the command.

For example, to create a new pod in the cluster, you would use the following kubectl command: `kubectl create pod <pod-name>`. To view information about a specific pod, you would use the following command: kubectl get pod <pod-name>.

In addition to these basic concepts, kubectl also supports more advanced features, such as custom resource definitions, plugins, and extensions, which allow you to extend its functionality and tailor it to your specific needs.

### kubectl Cheat Sheet: Must Know Operations
Here are some of the [must-know commands for kubectl](https://komodor.com/learn/the-ultimate-kubectl-cheat-sheet/) to interact with Kubernetes resources:
_Namespaces_
Kubernetes namespaces are a way to partition resources in a cluster into separate, isolated environments. Each namespace provides a unique scope for resources, allowing you to organize and manage resources in a way that is appropriate for your application. Here are some commands for managing namespaces:

- The `kubectl get namespaces` command is used to list all of the namespaces in a cluster. It returns a list of all of the namespaces, along with information such as the status and age of each namespace.
- The `kubectl create namespace <namespace name>` command is used to create a new namespace in the cluster. This command creates a new namespace with the specified name, and you can then use the namespace to isolate resources and manage them separately from other resources in the cluster.
- The `kubectl config set-context --current --namespace=<namespace name>` command is used to set the current namespace for the kubectl context. This command updates the context to use the specified namespace, allowing you to interact with resources in that namespace without having to explicitly specify the namespace each time.
- The `kubectl delete namespace <namespace name>` command is used to delete a namespace from the cluster. This command deletes the specified namespace and all of the resources it contains, freeing up resources and removing the namespace from the cluster.

_Nodes_
In a Kubernetes cluster, a node is a worker machine that runs containers. Nodes are the underlying infrastructure that runs the applications and services in a cluster. They are managed by the master node, which is responsible for scheduling and managing containers on the worker nodes:

The `kubectl get nodes` command is used to list all of the nodes in a cluster. This command returns a list of all of the nodes, along with information such as the status, role, and version of each node. 

The `kubectl top node <node name>` command is used to display resource usage information for a specific node. This command provides information such as the CPU and memory usage, as well as the number of containers running on the node.

The `kubectl cordon <node name>` command is used to mark a node as unschedulable, meaning that no new pods will be scheduled on the node. The kubectl uncordon <node name> command reverses this and marks a node as schedulable, allowing new pods to be scheduled on the node.

In the above examples, ‘worker’ is the name of the node.

The `kubectl drain node <node name>` command is used to drain a node in preparation for maintenance. This command gracefully evacuates all of the pods from the node, rescheduling them on other available nodes in the cluster. This allows you to safely perform maintenance on a node without disrupting the applications and services running in the cluster.


_Pods and Deployments_
Pods and deployments are resources in a Kubernetes cluster that can be managed using the following commands:

The `kubectl get` command is used to list resources in a cluster. For example, kubectl get pods lists all of the pods in the cluster, and kubectl get deployments lists all of the deployments in the cluster.

The `kubectl create` command is used to create new resources in a cluster. For example, kubectl create -f <file.yaml> creates a new pod, deployment, or secret based on the configuration defined in the specified YAML file.

Use the following YAML file to create a pod:

```
apiVersion: v1 
kind: Pod 
metadata: 
  name: nginx 
spec: 
  containers: 
  - name: nginx 
    image: nginx:1.14.2 
    ports: 
    - containerPort: 80

```
Save this file as app.yaml

- The `kubectl delete` command is used to delete resources from a cluster. For example, kubectl delete pod <pod-name> deletes a specific pod from the cluster.

- The `kubectl describe` command is used to display detailed information about a specific resource. For example, kubectl describe pod <pod-name> returns detailed information about a specific pod, including its status, events, and logs.

## 3 Little-Known kubectl Operations You Might Find Useful

1. Editing Resources
The `kubectl edit `command is used to edit the configuration of a resource in a cluster. For example, kubectl edit deployment <deployment-name> opens an editor to edit the configuration of a specific deployment.

Note: We used a sample file from web to create a deployment (you can download YAML from [this link](https://raw.githubusercontent.com/GoogleCloudPlatform/kubernetes-engine-samples/main/hello-app/manifests/helloweb-deployment.yaml)):

We can now edit the helloweb deployment using the following command: 

Kubectl edit deployment helloweb


2. Working with Storage Volumes
Here are kubectl commands for [managing Kubernetes volumes](https://bluexp.netapp.com/blog/cvo-blg-kubernetes-storage-an-in-depth-look):

`kubectl get pv`: Retrieving information about PersistentVolumes (PVs)

`kubectl describe pv X`: These commands will retrieve detailed information about the specified PV, including its configuration, status, and associated events.

`kubectl delete pv X`: These commands will delete the specified PV from your cluster.

`kubectl cp`: This command is used to copy files and directories between a pod and the local file system. For example, you can use this command to copy data from a volume mounted in a pod to your local file system for backup or analysis.


3. Working with DaemonSets
DaemonSets are a type of Kubernetes resource that ensure that a copy of a pod runs on every node in a cluster, or on a specific subset of nodes. This is useful for running system-level services that need to be present on every node, such as logging agents or monitoring agents.

The `kubectl create -f daemon.yaml` command is used to create a new DaemonSet in the cluster. This command creates a new DaemonSet with the specified name, and the specified pod is scheduled to run on every node in the cluster. The DaemonSet ensures that the specified pod is running and healthy on all of the nodes, and it will automatically reschedule the pod if it fails or if a node is added or removed from the cluster.

In the following example, we use following sample YAML file:

```
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: my-fluentd-elasticsearch-daemonset
  namespace: kube-system
  labels:
    k8s-app: fluentd-logging
spec:
  selector:
    matchLabels:
      name: fluentd-elasticsearch
  template:
    metadata:
      labels:
        name: fluentd-elasticsearch
    spec:
      tolerations:
      - key: node-role.kubernetes.io/master
        effect: NoSchedule
      containers:
      - name: fluentd-elasticsearch
        image: quay.io/fluentd_elasticsearch/fluentd:v2.5.2
        resources:
          limits:
            memory: 200Mi
          requests:
            cpu: 100m
            memory: 200Mi
        volumeMounts:
        - name: varlog
          mountPath: /var/log
        - name: varlibdockercontainers
          mountPath: /var/lib/docker/containers
          readOnly: true
      terminationGracePeriodSeconds: 30
      volumes:
      - name: varlog
        hostPath:
          path: /var/log
      - name: varlibdockercontainers
        hostPath:
          path: /var/lib/docker/containers
```

## Conclusion
In conclusion, kubectl is a powerful and essential tool for managing and interacting with a Kubernetes cluster. It provides a user-friendly interface for performing various operations to deploy, manage, and scale containerized applications. The kubectl command-line tool lets you manage your applications’, view logs, troubleshoot issues, and improve performance. Understanding the basics of kubectl, including the key resources and commands, is crucial for effectively managing a Kubernetes cluster.