Resources

kubectl Cheat Sheet: 10 Critical Commands & Examples

November 30, 2021

The kubectl command line tool can help you perform almost any action on your Kubernetes cluster without making API calls directly. This roundup covers 10 of the most commonly used commands.

Tyler Charboneau
Software Engineer

Kubernetes is the most popular containerized orchestration system, and company deployments range from simple to complex. Whatever your use case, maintaining fine-grained control over your Kubernetes clusters is possible via the command line—AKA <terminal inline>kubectl<terminal inline>.

This interface lets you execute powerful commands that directly impact core configurations. It’s a bare-bones user command center that’s siloed from popular Kubernetes GUIs—like Kubernetes Dashboard, Lens, or kubenav.

By following some easy syntax rules, using <terminal inline>kubectl<terminal inline> is relatively straightforward. The CLI supports Windows, Mac, and Linux operating systems; simply choose the appropriate install package to get started. Once the process is complete, you’re free to use <terminal inline>kubectl<terminal inline>. The controls available through the GUI are somewhat limited, so the CLI is geared more toward power users.

However, <terminal inline>kubectl<terminal inline> is surprisingly approachable, depending on what you want to achieve.

I’ve chosen the following ten commands based on their usefulness within Kubernetes. Every developer should have these commands in their toolbox, since they can accomplish quite a lot without massive effort. Efficiency is key when it comes to managing infrastructure; these commands should make your life just a little bit easier.

Quick Notes on Syntax

Before you jump into <terminal inline>kubectl<terminal inline>, it’s important to have a basic understanding of how commands are structured. All commands use the following structure in the CLI—and keeping each component in order is critical:


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

What does each piece mean?

Command

The <terminal inline>command<terminal inline> portion describes what sort of operation you want to perform—namely <terminal inline>create<terminal inline>, <terminal inline>describe<terminal inline>, <terminal inline>get<terminal inline>, <terminal inline>apply<terminal inline>, and <terminal inline>delete<terminal inline>. You can perform these commands on one or more resources, since it’s possible to designate multiple resources within a single command.

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

TYPE

The <terminal inline>TYPE<terminal inline> attribute describes the kind of resource <terminal inline>kubectl<terminal inline> is targeting. What are these resources, exactly? Things like pods, services, daemonsets, deployments, replicasets, statefulsets, Kubernetes jobs, and cron jobs are critical components within the Kubernetes system. Because they impact how your deployments behave, it makes sense that you’d want to modify them.

NAME

The <terminal inline>NAME<terminal inline> field is case sensitive and specifies the name of the resource in question. Tacking a name onto a command restricts that command to that sole resource. Omitting names from your command will pull details from all resources, like pods or jobs.

Flags

Finally, <terminal inline>flags<terminal inline> help denote special options or requests made to a certain resource. They work as modifiers that override any default values or environmental variables.

Now, it’s time to jump into our command roundup!

10 Recommended Kubectl Commands

These commands will help you better manage and understand your Kubernetes deployment as it evolves. I’ve included a variety of command types, and explained each, so you’ve got a quick cheat sheet readily available.

1. List all namespace services

Namespaces are incredibly important in Kubernetes. They’re a mechanism for isolating certain resource groups within a cluster, and then managing them accordingly. Additionally, visibility is critical within Kubernetes. Understanding how services are distributed helps immensely with diagramming or planning deployment changes.

Use this command to summon a list of all services in the current namespace:


kubectl get services

To retrieve a list of services in all namespaces, simply append the previous command like so:


kubectl get pods --all-namespaces

2. Retrieve details on your nodes

Nodes represent virtual or physical machines that act as worker machines within Kubernetes. They’re governed by the control plane and include the pods and containers needed to run your services. Understanding the status, readiness, and age of those nodes can shed light on your deployment’s age.

Because Kubernetes can support up to 5,000 nodes per cluster, it’s not uncommon for these nodes to come and go. Additionally, using different combinations of worker and master nodes can help optimize system performance. It’s helpful to know which nodes are which. Use this command to grab a node’s overall status:


kubectl get nodes

This grabs each node’s name, status (<terminal inline>running<terminal inline>, <terminal inline>ready<terminal inline>, <terminal inline>inactive)<terminal inline>, roles (<terminal inline>master<terminal inline>, <terminal inline>worker<terminal inline>, <terminal inline>controlplane<terminal inline>, <terminal inline>etcd<terminal inline>), age, and Kubernetes version.

3. Create a new namespace with a unique name

We’ve touched on the importance of namespaces when it comes to organizing Kubernetes resources. While managing Kubernetes at scale, it’s common for resources to multiply—either through daily activity, or out of necessity to better maintain the system. You might need to create new namespaces to keep Kubernetes tidy and well-configured.

Use this command to create a new namespace. Name it whatever you’d like (as long as that name isn’t already taken):


kubectl create ns hello-there

<terminal inline>kubectl<terminal inline> will display a message confirming successful creation of your new namespace. From there, you’re free to add resources as desired.

4. Leverage your files to configure Kubernetes

While some changes and settings are easily applicable within Kubernetes through commands alone, others require external configuration files for reference. While it’s possible to use the STDIN method instead, Kubernetes tends to recommend that you use either a JSON or YAML file for these configurations.

To leverage a config file and alter your resources, use the following command:


kubectl apply -f config.yaml

The CLI will confirm successful execution of this command when complete.

5. List all running pods in a namespace

Pods are the smallest deployable units of computing that you can create and manage in Kubernetes. One pod contains one running process in your cluster, so pod counts can increase dramatically as workloads increase. Accordingly, pods are deleted when they’re no longer needed or when a process is completed.

Because pods are so crucial, tracking which ones are running can help us better understand active processes and perhaps dig into active services. Enter this command:


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

6. Understand your cluster services

Your cluster contains nodes, pods, and containers—and ultimately the services running atop your infrastructure. It’s not uncommon for numerous services to exist in a cluster, and these may become harder to track over time.

Kubernetes is also inherently network-based, since service instances are assigned IP addresses throughout their life cycles. The same goes for other resources.

To display endpoint information (name, resource type, etc.) for your masters and services, type this simple command:


kubectl cluster-info

7. Request service logs

Logs are chock full of information that tell you how your services are running, which notable events occurred, and at what times these events took place. These human-readable lists of details can help you retrospectively investigate (and later fix) any outstanding deployment issues.

Services typically generate plenty of log files; what if a service shuts down, or behaves erratically? Use this command to help troubleshoot:


kubectl logs -f <service_name>

8. Reveal your secrets

Secrets are the passwords, credentials, keys, and more that help your services (and Kubernetes) run effectively at any given time. Without this data, proper authentication and authorization are impossible. Managing these secrets is essential—which is tough if you don’t know them.

Use the following command to fetch a list of all Kubernetes secrets:


kubectl get secrets

9. Keeping track of events

Kubernetes events tell you when resources undergo state changes, encounter errors, or need to broadcast system-wide messages for whatever reason. These objects provide a record of any notable activity that raises eyebrows in Kubernetes.

Summon a list of all resource-based events with this quick command:


kubectl get events

10. Leverage new DaemonSets

Kubernetes DaemonSets ensure that all specific nodes run at least one copy of a pod. Because of this, DaemonSets can help control distributed processes across your system. It’s possible to then run sidecar services (storage, logs collection, monitoring) within those nodes to boost observability. DaemonSets are extremely efficient. At ContainIQ, we leverage DaemonSets to deliver our Kubernetes native monitoring solution.

Use this command to create a new, named DaemonSet:


kubectl create daemonset <daemonset_name>

DaemonSets are described using a configuration file. You can also use the <terminal inline>apply<terminal inline> command to apply any configs.

Final Thoughts

Consider this list a good starting point for your Kubernetes administrative journey. These commands are meant to be relatively simple, user-friendly, and varied based on overall functionality. Hopefully it hit on many different Kubernetes components and offered some quick management tips via <terminal inline>kubectl<terminal inline>. These commands are extremely powerful, and are critical for team members of all skill levels.

Looking for an out-of-the-box monitoring solution?

With a simple one-line install, ContainIQ allows you to monitor the health of your cluster with pre-built dashboards and easy-to-set alerts.

Article by

Tyler Charboneau

Software Engineer

Tyler is a hardware-software devotee and researcher. He specializes in simplifying the complex while speaking effectively to all audiences. Tyler has a Bachelor of Arts degree from the University of Michigan and is a self-taught software engineer. His work has been published on a number of leading technology blogs from companies including Veeam, Launch Darkly, and others.

Read More