Kubectl Cheat Sheet: Common Commands Made Simple

Kubectl Cheat Sheet

Running a Kubernetes cluster isn’t always simple. Some days, it’s a dozen deployments running fine. Other days, it’s a pod in CrashLoopBackOff and a service you swore was working yesterday.

Anyone who manages clusters knows how it goes. The more moving parts you add, the easier it is to forget a command you swear you knew.

This kubectl cheat sheet isn’t trying to be fancy. It’s the real stuff you use every day. The quick things. The little flags you can never quite remember when production’s on fire. If you’ve ever paused mid-rollout and thought, “wait, what’s that command again,” this is for you.

Read more on Palark website

Understanding Kubernetes and Kubectl

Kubernetes is what keeps containerized applications running without you babysitting them all day. It takes care of the boring parts: deploying containers, keeping them alive, scaling them when traffic spikes, and spreading them across your servers (or “nodes”). The control plane makes those decisions. The worker nodes do the heavy lifting, each one running pods that hold your containers.

The real magic is how it keeps everything steady. The best part is how Kubernetes keeps things steady. When a container dies, it comes back.

For companies running microservices, it’s become the backbone of modern infrastructure. It handles the chaos so teams can focus on shipping updates instead of putting out fires. Around 84% of organizations using containers now rely on Kubernetes in some form – that’s how far it’s spread.

kubectl is how you tell Kubernetes what to do. You type a command, it hits the API, Kubernetes reacts. That’s the whole flow. It’s what you use to check what’s running, fix problems, or push new changes. You’ll do everything with it: pulling logs, scaling pods, cleaning up the mistakes you just made. After a while it’s all muscle memory.

Basic Kubectl Command Syntax

You’ll start to see a pattern after a few runs. All the commands look the same:

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

That’s the structure. Doesn’t change.

  • Command: what you’re doing. get, apply, delete, edit, describe, whatever.
  • TYPE: the kind of thing you’re working with. A pod, service, deployment, node, job, secret, pick one.
  • NAME: optional. Leave it out if you want to hit all of them.
  • Flags: small tweaks. Change output, switch namespaces, filter, sort, stuff like that.

What You Actually Manage With Kubectl

Before you get too deep into commands, it helps to know the pieces you’re poking at.

  • Cluster: the whole setup. One or more nodes managed by the control plane. Everything else lives inside it.
  • Node: one machine in that cluster. Could be a VM, could be real hardware. Runs containers through Docker, containerd, or whatever runtime you use.
  • Pod: the smallest piece. Usually one container, sometimes a couple. They share storage and a network. They come and go; they’re not permanent.
  • Deployment: looks after your pods. Keeps the number you want running, handles rollouts and rollbacks. You tell it what “normal” looks like, it tries to keep things there.
  • Service: gives your pods a steady name and address so you don’t care when they get replaced. That’s how traffic finds them.
  • Namespace: a way to keep stuff separated. Dev, staging, prod: all in the same cluster but not tripping over each other.

Kubectl Basic Commands (Information Retrieval)

First, you need to know what’s running, what’s healthy, and what’s not. These are the commands every engineer reaches for first: the ones that tell you what’s really happening.

  • kubectl cluster-info: This shows you where the cluster lives: the API server address, core services, and endpoints. If this command fails, stop right there. You’re not connected.
  • kubectl get nodes: Lists nodes in the cluster, their status, role, version, and uptime. You’ll spot trouble fast when a node isn’t Ready. It’s usually the first clue that something deeper is wrong.
  • kubectl get pods: The classic. It lists all pods in the current namespace. When something’s off – a pod in CrashLoopBackOff or one that never gets past Pending, this is where you notice.
  • kubectl get services: Shows every service that exposes your apps to traffic. The output tells you how each service is wired up – whether it’s ClusterIP, NodePort, or LoadBalancer — along with the ports and internal IPs.
  • kubectl get deployments: Lists deployments and shows if the replica counts line up. When they don’t, it means pods failed or the rollout never finished.

These are the heartbeat checks. The first five lines you run in the morning.

Formatting and Output Options

Sometimes kubectl can drown you in output. These help keep it manageable.

  • kubectl get pods -o wide: Adds columns for pod IPs and which node they’re on. Nice for checking traffic paths or debugging networks.
  • kubectl get deployment nginx-deployment -o yaml: Prints the YAML for that deployment. Good when you need to see how something’s actually set up.
  • kubectl get pods -o json: Gives you JSON output. Best for scripts or when you want to filter things using jq.

You’ll mix in these flags without thinking after a while. It just becomes part of how you work.

Managing Resources

You’ll spend most of your time managing pods – creating, deleting, checking logs, jumping inside them.

Pod Management

Pods do the heavy lifting, and you’ll end up controlling them a lot.

  • kubectl run nginx –image=nginx: Starts a quick single NGINX pod from Docker Hub. Great for testing or demos, not what you’d do in production though.
  • kubectl delete pod nginx: Removes a specific pod. If it’s part of a deployment, Kubernetes quietly replaces it.
  • kubectl describe pod nginx-deployment-7d64c5f5d9-2xkwm: Shows detailed info – events, container states, volume mounts, all of it. Useful when a pod keeps restarting.
  • kubectl logs nginx-deployment-7d64c5f5d9-2xkwm: Pulls logs from the container. Add -f to follow them live during startup or debugging.
  • kubectl exec -it nginx-deployment-7d64c5f5d9-2xkwm — /bin/sh: Opens a shell inside the container.

Deployment Management

Deployments are where most of the real work happens. These are your go-to commands.

  • kubectl create deployment nginx-deployment –image=nginx: Spins up a new deployment fast. Perfect for test runs. For anything real, keep YAML in version control.
  • kubectl scale deployment nginx-deployment –replicas=4: Adjusts the number of pod replicas running for this deployment.
  • kubectl set image deployment/nginx-deployment nginx=nginx:1.21: Updates the container image version, triggering a rolling update.
  • kubectl delete deployment nginx-deployment: Removes the deployment and all its managed pods. Use with caution in production environments.

Service Management

Services handle traffic so you don’t have to think about IPs.

  • kubectl expose deployment nginx-deployment –port=80 –type=LoadBalancer: Opens it up on port 80 and sets up a load balancer if your cloud supports it.
  • kubectl describe service nginx-service: Shows detailed service configuration, including endpoints (the pods backing this service), selectors, and port mappings.
  • kubectl delete service nginx-service: Removes the service, stopping external access to the deployment while leaving the pods running.

Namespace Management

Namespaces help organize cluster resources:

  • kubectl get namespaces: Lists all namespaces in your cluster. Fresh installations include default, kube-system, kube-public, and kube-node-lease.
  • kubectl create namespace nginx-namespace: Creates a new namespace for logical separation of resources. Many organizations use namespaces to separate environments like development, staging, and production.
  • kubectl delete namespace nginx-namespace: Deletes the namespace and everything inside. Be sure before you hit Enter.
  • kubectl config set-context –current –namespace=nginx-namespace: Switches your current context. Saves typing -n over and over again.

Configuration Management

Think of declarative configs as Kubernetes’ version of “remember what I said.”

  • kubectl apply -f nginx-deployment.yaml: Applies the configuration defined in a YAML file, creating or updating resources as needed. This is the preferred management approach for production systems.
  • kubectl delete -f nginx-deployment.yaml: Removes all resources defined in the specified file.
  • kubectl get all: Lists all common resource types in the current namespace—a quick way to survey your environment.

Troubleshooting Commands

When things go wrong, these diagnostic commands are invaluable:

  • kubectl get events –sort-by=’.metadata.creationTimestamp’: Shows recent cluster events sorted chronologically, revealing what happened during failures or unexpected behavior.
  • kubectl describe pod problematic-pod-abc123: Inspects a pod in detail, including recent events that explain why it might be failing to start or experiencing crashes.
  • kubectl logs -f nginx-deployment-7d64c5f5d9-2xkwm: Follows application logs in real-time, essential for observing behavior during troubleshooting.
  • kubectl top nodes: Displays CPU and memory usage for each node, helping identify resource bottlenecks.
  • kubectl top pods: Shows resource consumption for pods, useful for capacity planning and performance investigation.

Advanced Operations

Rollout Management

  • kubectl rollout status deployment/nginx-deployment: Tracks the progress of an ongoing rollout.
  • kubectl rollout history deployment/nginx-deployment: Shows the revision history of a deployment.
  • kubectl rollout undo deployment/nginx-deployment: Reverts to the previous deployment revision.
  • kubectl rollout restart deployment/nginx-deployment: Triggers a restart of all pods in the deployment.

Editing Live Resources

  • kubectl edit deployment nginx-deployment: Opens the deployment configuration in your default editor for live changes.
  • kubectl patch deployment nginx-deployment -p ‘{“spec”:{“replicas”:3}}’: Applies a partial update to a resource.

Port Forwarding

  • kubectl port-forward pod/nginx-deployment-7d64c5f5d9-2xkwm 8080:80: Forwards local port 8080 to port 80 on the specified pod.
  • kubectl port-forward service/nginx-service 8080:80: Forwards to a service instead of a specific pod.

Resource Management

  • kubectl delete pod –field-selector=status.phase==Failed: Removes all pods in a Failed state.
  • kubectl drain node-1 –ignore-daemonsets: Safely evicts all pods from a node for maintenance.
  • kubectl cordon node-1: Marks a node as unschedulable without evicting existing pods.
  • kubectl uncordon node-1: Makes a node schedulable again after maintenance.

Context and Configuration

  • kubectl config view: Displays the current kubeconfig file.
  • kubectl config get-contexts: Lists all available contexts.
  • kubectl config use-context production-cluster: Switches to a different cluster context.

Secret and ConfigMap Management

  • kubectl create secret generic db-password –from-literal=password=secret123: Creates a secret from a literal value.
  • kubectl create configmap app-config –from-file=config.properties: Creates a ConfigMap from a file.
  • kubectl get secrets: Lists all secrets in the current namespace.

Backup and Disaster Recovery with Trilio

Backups aren’t optional in production. They’re the difference between fixing an incident in minutes versus explaining to your boss why weeks of data just vanished. Kubernetes doesn’t come with built-in backup tools that understand how applications work. That’s where solutions like Trilio come in.

Trilio for Kubernetes handles backups and restores the way Kubernetes was meant to. It doesn’t just copy volumes or files. It understands how resources connect, how apps fit together. That means the backups are application-consistent, not just snapshots. When something breaks, you can restore everything – pods, deployments, services, ConfigMaps, Secrets – exactly as they were.

Creating a Backup Target

Start by creating a Secret to hold your AWS credentials. You’ll need this so Trilio can talk to your object storage.

apiVersion: v1
kind: Secret
metadata:
name: sample-s3-secret
type: Opaque
stringData:
accessKey: YOUR_ACCESS_KEY
secretKey: YOUR_SECRET_KEY

Once that’s in place, define the backup target. This tells Trilio where to send the data.

apiVersion: triliovault.trilio.io/v1
kind: Target
metadata:
name: sample-s3-target
spec:
type: ObjectStore
vendor: AWS
objectStoreCredentials:
credentialSecret:
name: sample-s3-secret
thresholdCapacity: 100Gi

That’s your backup destination – in this case, S3.

Defining Backup Plans and Policies

Now create a backup plan. This defines what you’re backing up and where it’s going.

apiVersion: triliovault.trilio.io/v1
kind: BackupPlan
metadata:
name: nginx-backup-plan
namespace: nginx-namespace
spec:
backupConfig:
target:
name: sample-s3-target
namespace: default

You’ll probably want a policy too, so you can control retention.

apiVersion: triliovault.trilio.io/v1
kind: Policy
metadata:
name: sample-policy
spec:
retention:
type: maxBackups
latest: 5

That example keeps the five most recent backups and clears out the older ones automatically.

Creating and Verifying Backups

To create and check a backup:

  • Apply your definition file using kubectl apply -f sample-backup.yaml.
  • Then verify it with kubectl get backups -n nginx-namespace.

Trilio doesn’t just grab containers – it captures the full state: Deployments, Services, ConfigMaps, Secrets, and relationships between them. When you restore, the application comes back as a working unit, not a pile of disconnected resources.

Restore Operations

When something goes wrong, restoring is straightforward. Define a restore object like this:

apiVersion: triliovault.trilio.io/v1
kind: Restore
metadata:
name: nginx-restore
namespace: nginx-namespace
spec:
source:
type: Backup
backup:
name: nginx-backup-20241013
restoreNamespace: nginx-namespace

Apply it and then check its status with kubectl get restore nginx-restore -n nginx-namespace.

You’ll see Trilio rebuild the application layer by layer – same pods, same configurations, same networking.

In production environments where downtime isn’t an option, the key isn’t just running backups but making sure restores actually work. Integrating automated testing and monitoring ensures your recovery plans don’t fail when you need them most.

Kubectl Best Practices

These are the habits that keep clusters sane when everything scales up and the number of moving parts triples overnight.

  • Use namespaces: Keep things separate. Split workloads by team, environment, or app so people don’t trip over each other. Namespaces help enforce policies and limits too – a small thing that saves hours later.
  • Label and annotate resources: Give your objects names that mean something. It feels optional at first, but when you’re managing thousands of pods, labels make filtering, monitoring, and searching fast.
  • Use declarative configs: Don’t rely on live commands. Store YAML in Git for versioning, reviews, and easy rollbacks.
  • Set resource limits: Always define CPU and memory limits. It keeps one app from starving everything else.
  • Use role-based access (RBAC): Give each person just enough permission to do their job. It prevents both mistakes and misuse. Least privilege is the safe default.
  • Keep clusters clean: Delete what you’re not using. Old test namespaces, orphaned services, stray pods – they add up. Less clutter means fewer surprises, better performance, and a smaller attack surface.

Once you’re running at enterprise scale, these become survival rules. With hundreds of microservices and thousands of pods, small lapses turn into real incidents fast.

Getting Help and Autocompletion

Even veterans forget syntax sometimes. That’s why the built-in help commands exist.

  • kubectl –help
  • kubectl get –help
  • kubectl create deployment –help

Enable Bash autocompletion to accelerate your workflow:

kubectl completion bash | sudo tee /etc/bash_completion.d/kubectl > /dev/null

source /etc/bash_completion.d/kubectl

Once that’s done, hit Tab after typing a command. You’ll get suggestions for commands, resource types, even resource names from your cluster. It feels small, but it speeds up your workflow more than you’d expect.

The Ultimate Kubectl Cheat Sheet

Kubectl is the multi-tool of Kubernetes. One command line utility that can check pods, pull logs, deploy code, or handle entire clusters.

When you really learn it, you stop treating Kubernetes like a mystery and start steering it with confidence. These commands are your foundation. With practice, they turn into muscle memory, the kind of quick reflexes that make real ops work smooth.

Kubernetes never stays still, but a good workflow keeps you ahead of the chaos. Automate what you can, stay organized, and keep kubectl sharp. It’s the tool that turns a messy cluster into something you can actually control.

Charles Poole is a versatile professional with extensive experience in digital solutions, helping businesses enhance their online presence. He combines his expertise in multiple areas to provide comprehensive and impactful strategies. Beyond his technical prowess, Charles is also a skilled writer, delivering insightful articles on diverse business topics. His commitment to excellence and client success makes him a trusted advisor for businesses aiming to thrive in the digital world.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close