Learning to Use the Kubernetes Client Kubectl

Kubernetes Client Kubectl
Kubernetes Client Kubectl

This post focuses on essential techniques for utilizing the Kubernetes Command Line Interface (CLI), kubectl.

Use Case

You need to list Kubernetes resources, either to get an overview of what’s running in your cluster or to inspect specific resources.


The kubectl get command is your primary tool for listing Kubernetes resources. It’s versatile, allowing you to query a wide range of resource types within your cluster.

To list all pods:

$ kubectl get pods

To list multiple resource types, like services and deployments (avoid spaces after commas):

$ kubectl get services,deployments

To list a specific deployment by name:

$ kubectl get deployment <deployment-name>

To list virtually every resource in a namespace:

$ kubectl get all

This command doesn’t truly list all resources (some like secrets won’t be shown), but it provides a comprehensive overview of most common resources like pods, services, deployments, etc.

Efficiency Tip: Short Names Kubernetes resources often have short names, making your commands quicker to type. For example:

  • configmaps (aka cm)
  • daemonsets (aka ds)
  • deployments (aka deploy)
  • endpoints (aka ep)
  • events (aka ev)
  • horizontalpodautoscalers (aka hpa)
  • ingresses (aka ing)
  • namespaces (aka ns)
  • nodes (aka no)
  • persistentvolumeclaims (aka pvc)
  • persistentvolumes (aka pv)
  • pods (aka po)
  • replicasets (aka rs)
  • replicationcontrollers (aka rc)
  • resourcequotas (aka quota)
  • serviceaccounts (aka sa)
  • services (aka svc)

These abbreviations can significantly speed up your workflow.

Further Insights: Leveraging autocompletion with kubectl can greatly enhance your productivity by reducing the need to memorize or type out full resource names. Most shell environments (bash, zsh, etc.) support kubectl autocompletion, and setting it up can save you a lot of time and effort.

Efficiently Deleting Kubernetes Resources

Use Case

You need to remove certain resources from your Kubernetes cluster, possibly to clean up or reorganize.


kubectl delete is the command designed for removing resources from your Kubernetes cluster. Its versatility allows for the deletion of individual resources, entire namespaces, or resources filtered by labels.

Deleting a Namespace and Its Contents: To delete a specific namespace and all resources within it:

$ kubectl delete ns my-app

This action will remove the my-app namespace and all contained resources. Remember, the default, kube-public, and kube-system namespaces are essential to Kubernetes and should not (or in some cases, cannot) be deleted.

Deleting All Resources in a Namespace: If you need to clear a namespace without deleting it:

$ kubectl delete all --all -n <namespace>

This command wipes all standard resources within the specified namespace.

Deleting Resources by Label: To target the deletion of resources by their labels, for instance, to remove services and deployments tagged with app=niceone:

$ kubectl delete svc,deploy -l app=niceone

Force Deletion of a Pod: For stubborn resources, like a non-terminating pod, you can force deletion:

$ kubectl delete pod hangingpod --grace-period=0 --force

Bulk Deletion Within a Namespace: To remove all pods within a specific namespace:

$ kubectl delete pods --all --namespace test


  • Avoid direct deletion of resources managed by higher-level constructs (e.g., Pods managed by a Deployment). Instead, manage the higher-level resource directly.
  • Be aware of cascading deletion, where deleting a parent resource (like a Custom Resource Definition, CRD) removes all its dependent objects. Kubernetes’ Garbage Collection mechanism controls this behavior.

Advanced Note: Adjusting the cascading deletion policy allows you to fine-tune what happens to dependent resources when a parent resource is removed. Understanding this can be crucial for managing complex deployments and ensuring a clean resource lifecycle.

Monitoring Kubernetes Object Changes in Real-Time

Use Case

Problem: You’re looking to keep an eye on the changes occurring to Kubernetes objects right from your terminal, seeking an interactive and dynamic way to observe these updates as they happen.


Solution: kubectl comes equipped with a --watch flag, designed specifically for this purpose. It allows you to monitor changes to your Kubernetes objects in real-time.

Watching Pods: To continuously watch pods and their status updates, you can use:

$ kubectl get pods --watch

This command effectively turns your terminal into a live dashboard, similar to how the top command works for system processes, displaying real-time updates as they occur.

Alternative Approach: While the --watch option is straightforward and tailored for kubectl, some users might prefer the output formatting provided by the watch command. This command refreshes the output of another command at a regular interval, thus providing a makeshift live update:

$ watch kubectl get pods

This method uses the watch utility to repeatedly execute the kubectl get pods command, refreshing the view at a default interval (normally 2 seconds). This can be particularly useful if you’re interested in a broader, more customizable view that updates periodically.

Updating Kubernetes Objects on the Fly

Use Case

You need to modify the configuration of a Kubernetes object, such as adjusting a deployment’s settings or adding labels to a pod.


Kubernetes provides the kubectl edit command, allowing you to directly edit the configuration of a running object in your default text editor. This command temporarily downloads the object’s definition, opens it in an editor, lets you make changes, and applies those changes when you save and exit the editor.

Example Usage:

  1. Deploy an nginx pod:$ kubectl run nginx --image=nginx
  2. Edit the nginx pod:$ kubectl edit pod/nginx In the editor, you might add a label to the pod’s metadata:labels: mylabel: "true" After saving and closing the file, you’ll see: pod/nginx edited

Setting the Editor: If the editor doesn’t open or you prefer a different editor, you can specify one by setting the EDITOR or KUBE_EDITOR environment variable. For instance, to use vi as the editor:

$ export EDITOR=vi


  • Not every change you make will trigger an immediate update to the object. Some properties are immutable, and attempting to change them will result in an error.
  • For specific modifications, such as updating a deployment’s container image, kubectl offers more direct commands like kubectl set image. This command specifically targets and updates container images within various Kubernetes objects (deployments, pods, etc.) and is more straightforward for certain types of updates.

Discussion: The kubectl edit command is a powerful tool for dynamically adjusting Kubernetes objects, offering a quick way to prototype changes or make immediate adjustments. However, for more systematic changes or production environments, it’s advisable to update the YAML definitions of your resources and apply them with kubectl apply, ensuring a traceable, version-controlled record of your cluster’s configuration.

Understanding Kubernetes Resources and Fields with kubectl explain

Use Case

Problem: You’re aiming to deepen your knowledge about specific Kubernetes resources, such as a Service, or you need clarification on the purpose and usage of specific fields within Kubernetes manifests. Knowing whether a field is required, optional, and its default values would also be beneficial.


Solution: Leverage the kubectl explain command. This command is incredibly useful for both beginners and experienced Kubernetes users alike, offering detailed descriptions and specifications of Kubernetes resources and their fields directly from the command line.

Exploring a Resource: To get detailed information about a Service, including its fields, descriptions, and types:

$ kubectl explain svc
KIND: Service

Service is a named abstraction of software service (for example, mysql)
consisting of local port (for example 3306) that the proxy listens on, and the
selector that determines which pods will answer requests sent through the proxy.

status <Object>
Most recently observed status of the service. Populated by the system.
Read-only. More info: https://git.k8s.io/community/contributors/devel/

apiVersion <string>
APIVersion defines the versioned schema of this representation of an
object. Servers should convert recognized schemas to the latest internal
value, and may reject unrecognized values. More info:

kind <string>
Kind is a string value representing the REST resource this object
represents. Servers may infer this from the endpoint the client submits
requests to. Cannot be updated. In CamelCase. More info:

metadata <Object>
Standard object's metadata. More info:

spec <Object>
Spec defines the behavior of a service. https://git.k8s.io/community/

This command provides a comprehensive overview of the Service resource, including an explanation of what the resource is, its structure, and details about each field.

Diving into Specific Fields: If you’re interested in understanding a specific field within a resource, such as svc.spec.externalIPs, kubectl explain can also target this level of detail:

$ kubectl explain svc.spec.externalIPs                                     KIND:       Service

FIELD: externalIPs <[]string>

externalIPs is a list of IP addresses for which nodes in the cluster will
also accept traffic for this service. These IPs are not managed by
Kubernetes. The user is responsible for ensuring that traffic arrives at a
node with this IP. A common example is external load-balancers that are not
part of the Kubernetes system.

This will output the type, applicable values, and a description of what the externalIPs field does, including how it’s used in the context of a Service.

Discussion: The kubectl explain command retrieves its information from the Kubernetes API’s Swagger/OpenAPI definitions, making it an authoritative source of information on the structure and specification of Kubernetes resources. It’s akin to having a comprehensive Kubernetes documentation at your fingertips.

Comparing explain with describe: It’s important to differentiate between kubectl explain and kubectl describe:

  • kubectl explain provides a schema-like overview of a Kubernetes resource type, detailing what fields it contains and how they are used.
  • kubectl describe, on the other hand, shows the current state and configuration of an instance of a resource (an object) in your cluster, such as the specific settings of a running pod or service.

Together, these commands offer powerful ways to not only understand the Kubernetes resources you’re working with but also to inspect the current configurations and statuses of those resources within your cluster.


  • Mohamed BEN HASSINE

    Mohamed BEN HASSINE is a Hands-On Cloud Solution Architect based out of France. he has been working on Java, Web , API and Cloud technologies for over 12 years and still going strong for learning new things. Actually , he plays the role of Cloud / Application Architect in Paris ,while he is designing cloud native solutions and APIs ( REST , gRPC). using cutting edge technologies ( GCP / Kubernetes / APIGEE / Java / Python )

    View all posts
You May Also Like