Kubectl Cheat Sheet: 100+ Essential Commands for Kubernetes Administration (2026 Guide)

Published: 2025-10-26
74 min read
Share:

kubectl is the primary command-line interface for Kubernetes. Whether you're deploying applications, investigating production incidents, managing multi-cluster environments, or automating CI/CD pipelines, mastering kubectl is one of the most valuable skills for Kubernetes administrators, DevOps engineers, Site Reliability Engineers (SREs), and platform teams.

Unlike graphical dashboards that expose only a subset of Kubernetes functionality, kubectl provides direct access to the Kubernetes API. Almost every Kubernetes operation—from creating workloads and inspecting cluster state to debugging failures and applying declarative infrastructure—can be performed through kubectl.

This cheat sheet is designed as both a quick reference and a practical learning guide. Rather than listing commands without context, it explains when to use them, why they matter, and common production considerations.


Executive Summary

This guide covers everything needed to become productive with kubectl in modern Kubernetes environments.

You'll learn how to:

  • Configure and manage multiple Kubernetes clusters
  • Work efficiently with kubeconfig files and contexts
  • Discover Kubernetes API resources
  • Format command output for automation
  • Inspect cluster health
  • Manage namespaces safely
  • Build production-ready command workflows
  • Understand common operational patterns used by platform engineering teams

By the end of this guide, you'll have a reference you can use daily regardless of whether you manage a local development cluster, Amazon EKS, Google Kubernetes Engine (GKE), Azure Kubernetes Service (AKS), OpenShift, or an on-premises Kubernetes installation.


What Is kubectl?

kubectl (pronounced cube-control) is the official Kubernetes command-line client. It communicates directly with the Kubernetes API Server and allows users to manage every Kubernetes resource supported by the cluster.

Instead of interacting with worker nodes directly, nearly every administrative action passes through the Kubernetes control plane.

Examples include:

  • Creating deployments
  • Scaling applications
  • Inspecting Pods
  • Viewing logs
  • Managing ConfigMaps
  • Creating Secrets
  • Updating Services
  • Performing rolling updates
  • Managing RBAC
  • Troubleshooting cluster issues

At a high level, the workflow looks like this:

User
   │
   ▼
kubectl
   │
HTTPS REST API
   │
   ▼
API Server
   │
   ▼
Kubernetes Control Plane
   │
   ▼
Worker Nodes

Every kubectl command ultimately translates into one or more Kubernetes API requests.

For example:

kubectl get pods

internally requests Pod objects from the Kubernetes API Server.


What Can kubectl Manage?

kubectl can manage virtually every Kubernetes resource, including:

  • Pods
  • Deployments
  • ReplicaSets
  • StatefulSets
  • DaemonSets
  • Jobs
  • CronJobs
  • Services
  • Ingresses
  • Namespaces
  • Nodes
  • ConfigMaps
  • Secrets
  • Persistent Volumes
  • Persistent Volume Claims
  • Storage Classes
  • Service Accounts
  • Roles
  • ClusterRoles
  • RoleBindings
  • Network Policies
  • Custom Resource Definitions (CRDs)

Because Kubernetes is API-driven, any resource exposed by the API can generally be managed through kubectl.


Why kubectl Matters in 2026

Kubernetes continues to evolve rapidly, but kubectl remains the standard administrative interface across virtually every Kubernetes distribution.

Modern platform engineering teams rely on kubectl for:

  • Production incident response
  • GitOps validation
  • Infrastructure automation
  • CI/CD pipelines
  • Multi-cluster operations
  • Security auditing
  • Resource troubleshooting
  • Cluster maintenance

Although dashboards such as Kubernetes Dashboard, Lens, OpenLens, and vendor-specific portals provide visual interfaces, they cannot replace the flexibility and automation capabilities of kubectl.

For example, identifying unhealthy Pods across every namespace is a single command:

kubectl get pods --all-namespaces

Likewise, exporting deployment manifests for GitOps review requires only:

kubectl get deployment frontend -o yaml

Because nearly every Infrastructure as Code workflow integrates with Kubernetes APIs, proficiency with kubectl remains essential.


Common Real-World Use Cases

In production environments, engineers frequently use kubectl to:

  • Diagnose CrashLoopBackOff errors
  • Monitor application rollouts
  • Investigate failed scheduling
  • Retrieve container logs
  • Connect temporarily to running containers
  • Verify RBAC permissions
  • Apply declarative configuration
  • Perform zero-downtime updates
  • Verify cluster health
  • Inspect networking resources

Most Kubernetes interview questions also assume familiarity with common kubectl workflows.


Installation & Version Compatibility

Before using kubectl, install a version compatible with your Kubernetes cluster.

Version Skew Policy

Kubernetes supports a limited client/server version difference.

As a general recommendation:

  • Keep kubectl within one minor version of the Kubernetes API Server.
  • Using much older clients may result in unsupported API behavior.
  • Using newer clients against significantly older clusters may expose unavailable features.

Always verify compatibility before performing production upgrades.


Verify Installed Version

kubectl version

Example:

Client Version: v1.34.x
Kustomize Version: v5.x.x

To retrieve server information:

kubectl version --short

or

kubectl version -o yaml

Install kubectl

Installation methods vary by operating system.

Linux users commonly install using:

curl

Package managers include:

  • apt
  • dnf
  • yum
  • zypper
  • snap

macOS users commonly install with:

brew install kubectl

Windows users typically install through:

  • winget
  • Chocolatey
  • Scoop

For production systems, always follow the installation instructions published in the official Kubernetes documentation to ensure binary integrity and compatibility.


Confirm Installation

kubectl version --client

Check executable path:

which kubectl

Windows:

where kubectl

Kubernetes Architecture Overview

Understanding where kubectl fits within Kubernetes makes troubleshooting much easier.

The Kubernetes architecture consists of two major parts.

Control Plane

Responsible for cluster management.

Components include:

  • API Server
  • Scheduler
  • Controller Manager
  • etcd
  • Cloud Controller Manager (optional)

Worker Nodes

Worker nodes execute application workloads.

Each node typically runs:

  • kubelet
  • kube-proxy (or an alternative implementation)
  • Container Runtime

How kubectl Communicates

kubectl
     │
     ▼
API Server
     │
     ▼
Authentication
     │
Authorization
     │
Admission Controllers
     │
     ▼
etcd

Every command travels through the Kubernetes API Server.

This means:

  • RBAC permissions apply.
  • Audit logs can capture operations.
  • Admission policies are enforced.
  • Mutating webhooks can modify requests.
  • Validating webhooks can reject requests.

kubectl Configuration & kubeconfig

kubectl stores connection information inside a configuration file called kubeconfig.

This file contains:

  • Clusters
  • Users
  • Credentials
  • Contexts
  • Default namespace

By default, it resides in:

Linux/macOS:

~/.kube/config

Windows:

%USERPROFILE%\.kube\config

View Configuration

kubectl config view

Display merged configuration:

kubectl config view --flatten

View raw configuration:

kubectl config view --raw

Use a Different kubeconfig File

kubectl --kubeconfig=config-dev.yaml get pods

Alternatively:

export KUBECONFIG=config-dev.yaml

Multiple files can be merged:

export KUBECONFIG=config-dev.yaml:config-prod.yaml

Then inspect:

kubectl config view

Display Current User

kubectl config view --minify

Display Current Namespace

kubectl config view --minify --output 'jsonpath={..namespace}'

Common kubeconfig Problems

Typical issues include:

  • Expired credentials
  • Incorrect API endpoint
  • Invalid certificates
  • Wrong context
  • Missing namespace
  • Authentication token expiration

Before troubleshooting Kubernetes itself, verify your kubeconfig.


Context Management

Contexts define which cluster, namespace, and user kubectl should use.

They are essential when working across multiple environments.


List Contexts

kubectl config get-contexts

Display Current Context

kubectl config current-context

Switch Context

kubectl config use-context production

Create Context

kubectl config set-context dev \
  --cluster=my-cluster \
  --user=developer \
  --namespace=development

Rename Context

kubectl config rename-context old-name new-name

Delete Context

kubectl config delete-context old-context

Change Default Namespace

kubectl config set-context --current --namespace=development

Verify:

kubectl config view --minify

Production Tip

Always confirm your current context before executing destructive commands.

Example:

kubectl config current-context

Accidentally deleting workloads from a production cluster is one of the most common operational mistakes in multi-cluster environments.


API Discovery

One of the most underused kubectl features is API discovery.

Rather than memorizing every Kubernetes object, you can ask the cluster which resources it supports.


List Available Resources

kubectl api-resources

Example output includes:

  • pods
  • deployments
  • services
  • configmaps
  • secrets
  • cronjobs
  • ingresses
  • persistentvolumeclaims

This command also lists Custom Resource Definitions (CRDs).


List API Versions

kubectl api-versions

Useful when troubleshooting deprecated APIs.


Explain Resource Fields

kubectl explain deployment

Inspect nested fields:

kubectl explain deployment.spec

Inspect containers:

kubectl explain deployment.spec.template.spec.containers

This is one of the fastest ways to understand Kubernetes manifests directly from the API schema.


Explain Recursive Structure

kubectl explain deployment --recursive

Ideal for learning resource definitions.


Output Formatting

One of kubectl's greatest strengths is flexible output formatting.

This makes it suitable for scripting, automation, GitOps, and CI/CD.


Default Output

kubectl get pods

Wide Output

kubectl get pods -o wide

Shows additional information such as:

  • Node
  • Pod IP
  • Internal IP
  • Scheduling location

YAML Output

kubectl get deployment nginx -o yaml

Useful for:

  • backups
  • debugging
  • GitOps
  • manifest generation

JSON Output

kubectl get pod nginx -o json

Commonly consumed by automation scripts.


Resource Name Only

kubectl get pods -o name

Example:

pod/frontend
pod/backend

Useful for shell pipelines.


Custom Columns

kubectl get pods \
-o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName

Ideal for dashboards and reports.


JSONPath

Retrieve individual fields:

kubectl get pod nginx \
-o jsonpath='{.status.podIP}'

Retrieve image names:

kubectl get pods \
-o jsonpath='{.items[*].spec.containers[*].image}'

JSONPath is frequently used in automation pipelines.


Save Output

kubectl get deployment api -o yaml > deployment.yaml

Cluster Information Commands

Cluster health checks are often the first step during troubleshooting.


Display Cluster Information

kubectl cluster-info

Displays:

  • API Server
  • CoreDNS
  • cluster endpoints

List Nodes

kubectl get nodes

Show extended information:

kubectl get nodes -o wide

Describe a Node

kubectl describe node worker-01

Useful for viewing:

  • Allocated resources
  • Labels
  • Taints
  • Capacity
  • Conditions
  • Events

Monitor Events

Newest first:

kubectl get events \
--sort-by=.metadata.creationTimestamp

Watch continuously:

kubectl get events --watch

View Component Health

Modern Kubernetes distributions expose health endpoints differently, but cluster readiness is commonly validated using:

kubectl cluster-info

and

kubectl get nodes

followed by:

kubectl get pods -A

to identify unhealthy control-plane workloads where applicable.


Namespace Commands

Namespaces provide logical isolation between workloads.

Typical environments include:

  • development
  • testing
  • staging
  • production

Using namespaces correctly simplifies resource organization, RBAC, quota management, and multi-team collaboration.


List Namespaces

kubectl get namespaces

or

kubectl get ns

Create Namespace

kubectl create namespace development

Describe Namespace

kubectl describe namespace development

Displays:

  • Labels
  • Resource quotas
  • Events
  • Status

Delete Namespace

kubectl delete namespace development

Deleting a namespace removes nearly all namespaced resources contained within it. Always verify the target before deletion.


Set Default Namespace

kubectl config set-context \
--current \
--namespace=development

List Resources Within a Namespace

kubectl get pods -n development

or

kubectl get all -n development

List Resources Across Every Namespace

kubectl get pods --all-namespaces

or

kubectl get pods -A

Apply a Manifest to a Namespace

kubectl apply \
-f deployment.yaml \
-n development

Delete All Pods in a Namespace

kubectl delete pods --all -n development

Use carefully in production environments.


Production Best Practices

  • Separate workloads by environment.
  • Avoid deploying everything into the default namespace.
  • Apply RBAC policies per namespace whenever possible.
  • Use ResourceQuotas and LimitRanges for shared clusters.
  • Adopt consistent namespace naming conventions across environments.
  • Verify the active namespace before running destructive commands.

Pod Management

Pods are the smallest deployable units in Kubernetes and the fundamental building blocks for running containerized workloads. A Pod can contain one or more tightly coupled containers that share networking, storage, and lifecycle.

In production environments, Pods are rarely created manually. Instead, controllers such as Deployments, StatefulSets, DaemonSets, or Jobs create and manage Pods automatically.


List Pods

Display Pods in the current namespace:

kubectl get pods

Short form:

kubectl get po

View Pods across all namespaces:

kubectl get pods --all-namespaces

or

kubectl get pods -A

Display additional details:

kubectl get pods -o wide

This includes:

  • Pod IP
  • Node
  • Ready status
  • Restart count
  • Age

Watch Pods in real time:

kubectl get pods --watch

Describe a Pod

kubectl describe pod frontend-7d77f4d8d-abcde

This command is invaluable during troubleshooting because it displays:

  • Container images
  • Resource requests
  • Resource limits
  • Mounted volumes
  • Environment variables
  • Events
  • Scheduling history
  • Probe failures
  • Restart reasons

When a Pod fails unexpectedly, kubectl describe should usually be your first diagnostic step.


View Pod Logs

Retrieve logs:

kubectl logs frontend-7d77f4d8d-abcde

Follow logs continuously:

kubectl logs -f frontend-7d77f4d8d-abcde

Retrieve logs from a specific container:

kubectl logs frontend-7d77f4d8d-abcde \
-c nginx

Display logs from the previous crashed container:

kubectl logs \
--previous \
frontend-7d77f4d8d-abcde

This is especially useful when diagnosing CrashLoopBackOff errors.


Execute Commands Inside a Pod

Open a shell:

kubectl exec -it frontend \
-- /bin/bash

Many lightweight images use BusyBox or Alpine and do not include Bash.

Use:

kubectl exec -it frontend \
-- /bin/sh

Run a single command:

kubectl exec frontend \
-- env

List files:

kubectl exec frontend \
-- ls /usr/share/nginx/html

Delete Pods

Delete a Pod:

kubectl delete pod frontend

Delete multiple Pods:

kubectl delete pods pod1 pod2 pod3

Delete Pods by label:

kubectl delete pods \
-l app=frontend

Delete all Pods in a namespace:

kubectl delete pods \
--all \
-n development

Force deletion:

kubectl delete pod frontend \
--force \
--grace-period=0

Force deletion should only be used when a Pod is stuck terminating.


View Pod YAML

kubectl get pod frontend \
-o yaml

View JSON:

kubectl get pod frontend \
-o json

Common Pod Status Values

Frequently encountered Pod states include:

  • Pending
  • Running
  • Succeeded
  • Failed
  • Unknown
  • CrashLoopBackOff
  • ImagePullBackOff
  • ErrImagePull
  • ContainerCreating
  • Terminating

Understanding these states significantly accelerates production troubleshooting.


Debugging Workflow

A common workflow for diagnosing Pod issues:

kubectl get pods

↓

kubectl describe pod

↓

kubectl logs

↓

kubectl logs --previous

↓

kubectl exec

↓

kubectl debug

Production Best Practices

  • Avoid creating standalone Pods in production.
  • Use Deployments or StatefulSets instead.
  • Configure readiness and liveness probes.
  • Define CPU and memory requests.
  • Define CPU and memory limits.
  • Keep Pods immutable whenever possible.
  • Use labels consistently.

Deployment Management

Deployments provide declarative management for stateless applications.

A Deployment manages:

  • ReplicaSets
  • Rolling updates
  • Rollbacks
  • Scaling
  • Self-healing

Production applications almost always use Deployments instead of standalone Pods.


List Deployments

kubectl get deployments

Short form:

kubectl get deploy

Across all namespaces:

kubectl get deploy -A

Describe a Deployment

kubectl describe deployment frontend

Displays:

  • Replica count
  • Strategy
  • Conditions
  • Events
  • Current image
  • Rollout history

Create a Deployment

kubectl create deployment nginx \
--image=nginx

Although useful for experimentation, production environments typically deploy YAML manifests rather than imperative commands.


Scale a Deployment

kubectl scale deployment frontend \
--replicas=5

Scale multiple Deployments:

kubectl scale deployment frontend backend \
--replicas=3

Update an Image

kubectl set image deployment/frontend \
nginx=nginx:1.28

Verify rollout:

kubectl rollout status deployment/frontend

Restart a Deployment

Restart Pods without changing the manifest:

kubectl rollout restart deployment/frontend

This is commonly used after updating ConfigMaps or Secrets.


Pause a Rollout

kubectl rollout pause deployment/frontend

Resume:

kubectl rollout resume deployment/frontend

Rollout Status

kubectl rollout status deployment/frontend

Watch until rollout completes.


Rollout History

kubectl rollout history deployment/frontend

Specific revision:

kubectl rollout history deployment/frontend \
--revision=3

Roll Back

Rollback to the previous revision:

kubectl rollout undo deployment/frontend

Rollback to a specific revision:

kubectl rollout undo deployment/frontend \
--to-revision=2

Delete Deployment

kubectl delete deployment frontend

Export Deployment

kubectl get deployment frontend \
-o yaml

Production Best Practices

  • Prefer declarative manifests over imperative creation.
  • Use rolling updates.
  • Configure readiness probes.
  • Configure liveness probes.
  • Configure resource requests.
  • Configure PodDisruptionBudgets where appropriate.
  • Monitor rollout status after every deployment.

ReplicaSets

ReplicaSets maintain a desired number of identical Pod replicas.

Although Deployments automatically manage ReplicaSets, understanding ReplicaSets helps during troubleshooting.


List ReplicaSets

kubectl get replicasets

Short form:

kubectl get rs

Describe ReplicaSet

kubectl describe rs frontend

Displays:

  • Replica count
  • Selector
  • Pod template
  • Events

Scale ReplicaSet

kubectl scale rs frontend \
--replicas=4

Generally, scale the Deployment rather than the ReplicaSet directly.


Delete ReplicaSet

kubectl delete rs frontend

Deleting a ReplicaSet also removes its managed Pods unless orphaning is specified.


View ReplicaSet YAML

kubectl get rs frontend \
-o yaml

Production Notes

  • Avoid manually editing ReplicaSets created by Deployments.
  • Treat ReplicaSets as implementation details.
  • Use Deployments for lifecycle management.

StatefulSets

StatefulSets manage workloads that require stable identities and persistent storage.

Unlike Deployments, StatefulSets preserve:

  • Pod identity
  • Network identity
  • Persistent storage
  • Ordered startup
  • Ordered shutdown

Common workloads include:

  • PostgreSQL
  • MySQL
  • MongoDB
  • Elasticsearch
  • Kafka
  • ZooKeeper
  • Redis Sentinel

List StatefulSets

kubectl get statefulsets

Short form:

kubectl get sts

Describe StatefulSet

kubectl describe statefulset mysql

Displays:

  • Replicas
  • Update strategy
  • PVC templates
  • Current Pods
  • Events

Scale StatefulSet

kubectl scale statefulset mysql \
--replicas=5

Pods are created sequentially:

mysql-0

↓

mysql-1

↓

mysql-2

This ordering is essential for distributed databases.


Restart StatefulSet

kubectl rollout restart statefulset/mysql

Check Rollout

kubectl rollout status statefulset/mysql

View Persistent Volume Claims

kubectl get pvc

Each StatefulSet replica generally receives its own dedicated PersistentVolumeClaim.


Delete StatefulSet

kubectl delete statefulset mysql

Deleting a StatefulSet does not automatically remove associated PersistentVolumeClaims unless the storage class and reclaim policy dictate otherwise.

Always verify storage retention policies before deletion.


Export StatefulSet

kubectl get statefulset mysql \
-o yaml

When to Use StatefulSets

Choose a StatefulSet when your application requires:

  • Stable hostnames
  • Persistent storage
  • Ordered deployment
  • Ordered scaling
  • Ordered termination
  • Stable network identity

For stateless web applications, use a Deployment instead.


Production Best Practices

  • Use persistent volumes for all stateful workloads.
  • Configure anti-affinity where appropriate.
  • Regularly back up persistent data.
  • Monitor storage utilization.
  • Test recovery procedures.
  • Avoid manual Pod deletion unless necessary.
  • Verify rollout completion before upgrading clustered databases.

DaemonSets

A DaemonSet ensures that a copy of a Pod runs on every eligible node in a Kubernetes cluster. As new nodes join the cluster, Kubernetes automatically schedules the DaemonSet Pod onto them. Likewise, when nodes are removed, the corresponding Pods are cleaned up automatically.

DaemonSets are commonly used for cluster-wide infrastructure services rather than application workloads.

Typical use cases include:

  • Log collection (Fluent Bit, Fluentd)
  • Metrics collection (Prometheus Node Exporter)
  • Container runtime monitoring
  • Security agents
  • Network plugins (CNI)
  • Storage plugins (CSI)
  • Node monitoring
  • Service mesh data planes in specific architectures

Unlike Deployments, DaemonSets do not use a replica count. Kubernetes ensures one Pod per eligible node by design.


List DaemonSets

kubectl get daemonsets

Short form:

kubectl get ds

Across all namespaces:

kubectl get ds -A

Describe a DaemonSet

kubectl describe daemonset fluent-bit

Useful information includes:

  • Desired Pods
  • Current Pods
  • Ready Pods
  • Node selector
  • Update strategy
  • Events

View DaemonSet YAML

kubectl get ds fluent-bit -o yaml

Restart a DaemonSet

kubectl rollout restart daemonset/fluent-bit

Monitor Rollout

kubectl rollout status daemonset/fluent-bit

View Rollout History

kubectl rollout history daemonset/fluent-bit

Update an Image

kubectl set image daemonset/fluent-bit \
fluent-bit=fluent/fluent-bit:latest

Delete a DaemonSet

kubectl delete daemonset fluent-bit

Production Best Practices

  • Restrict scheduling using node selectors or affinity rules when appropriate.
  • Define CPU and memory requests to avoid starving application workloads.
  • Monitor rollout progress during upgrades.
  • Avoid running privileged containers unless absolutely necessary.
  • Use tolerations for system-level DaemonSets that must run on control-plane or tainted nodes.

Jobs

A Job creates one or more Pods to execute a task until it completes successfully.

Unlike Deployments, Jobs are designed for finite workloads rather than continuously running services.

Common examples include:

  • Database migrations
  • Batch processing
  • Report generation
  • Machine learning tasks
  • Backup operations
  • Data imports
  • ETL pipelines

List Jobs

kubectl get jobs

Short form:

kubectl get job

Across all namespaces:

kubectl get jobs -A

Describe a Job

kubectl describe job database-migration

This displays:

  • Completion status
  • Retry count
  • Active Pods
  • Events
  • Pod template

Create a Job

kubectl create job \
database-migration \
--image=alpine

For production workloads, declarative manifests are recommended over imperative commands.


Monitor Job Progress

kubectl get jobs

Watch continuously:

kubectl get jobs --watch

View Job Pods

kubectl get pods \
-l job-name=database-migration

View Job Logs

kubectl logs job/database-migration

Delete a Job

kubectl delete job database-migration

Production Best Practices

  • Configure retry limits (backoffLimit).
  • Define resource requests and limits.
  • Set ttlSecondsAfterFinished to automatically clean up completed Jobs where appropriate.
  • Avoid long-running workloads that should instead be managed by Deployments.
  • Monitor failed Jobs and investigate underlying Pod events.

CronJobs

A CronJob schedules Jobs to run automatically according to a cron expression.

Each scheduled execution creates a new Kubernetes Job.

CronJobs are ideal for recurring administrative or operational tasks.

Common examples include:

  • Nightly backups
  • Log rotation
  • Report generation
  • Database cleanup
  • Cache refreshes
  • Security scans
  • Data synchronization

List CronJobs

kubectl get cronjobs

Short form:

kubectl get cj

Describe a CronJob

kubectl describe cronjob nightly-backup

Suspend a CronJob

Pause scheduled executions:

kubectl patch cronjob nightly-backup \
-p '{"spec":{"suspend":true}}'

Resume a CronJob

kubectl patch cronjob nightly-backup \
-p '{"spec":{"suspend":false}}'

View Created Jobs

kubectl get jobs

Delete a CronJob

kubectl delete cronjob nightly-backup

Example Schedule

Run every day at midnight:

0 0 * * *

Run every hour:

0 * * * *

Run every five minutes:

*/5 * * * *

Production Best Practices

  • Configure history limits for successful and failed Jobs.
  • Use meaningful schedule descriptions.
  • Ensure Jobs are idempotent.
  • Set appropriate concurrency policies.
  • Monitor execution failures through Job status and events.
  • Test cron schedules before deploying to production.

Services

Pods are ephemeral and their IP addresses can change over time. A Service provides a stable network endpoint that allows applications to communicate reliably.

Services use label selectors to route traffic to matching Pods.

Common Service types include:

  • ClusterIP
  • NodePort
  • LoadBalancer
  • ExternalName

List Services

kubectl get services

Short form:

kubectl get svc

Across all namespaces:

kubectl get svc -A

Describe a Service

kubectl describe service frontend

Key information includes:

  • Cluster IP
  • Endpoints
  • Port mappings
  • Selectors
  • Events

Create a Service

Expose an existing Deployment:

kubectl expose deployment frontend \
--port=80 \
--target-port=8080 \
--type=ClusterIP

Create a NodePort Service

kubectl expose deployment frontend \
--port=80 \
--type=NodePort

Create a LoadBalancer Service

kubectl expose deployment frontend \
--port=80 \
--type=LoadBalancer

This requires support from the underlying cloud provider or load balancer implementation.


View Endpoints

kubectl get endpoints

or

kubectl get ep

Endpoints identify the Pods currently backing a Service.


Export Service YAML

kubectl get svc frontend \
-o yaml

Delete a Service

kubectl delete service frontend

Service Types

ClusterIP

  • Default Service type
  • Internal cluster communication only

NodePort

  • Exposes the Service on each worker node
  • Commonly used for testing or bare-metal environments

LoadBalancer

  • Integrates with supported cloud provider load balancers
  • Recommended for external production traffic

ExternalName

  • Maps a Kubernetes Service to an external DNS name

Production Best Practices

  • Prefer ClusterIP for internal services.
  • Use Ingress or Gateway APIs for HTTP and HTTPS routing.
  • Avoid exposing NodePorts directly to the Internet.
  • Verify Service selectors match Pod labels.
  • Monitor endpoint availability during deployments.

Ingress

An Ingress manages external HTTP and HTTPS access to Services within a Kubernetes cluster.

Instead of exposing each application individually, an Ingress allows multiple Services to share a single entry point while routing traffic based on hostnames or URL paths.

Typical capabilities include:

  • Host-based routing
  • Path-based routing
  • TLS termination
  • HTTPS redirection
  • URL rewrites
  • Load balancing
  • Authentication integration (controller dependent)

Ingress resources require an Ingress Controller (such as NGINX Ingress Controller, Traefik, or cloud-native controllers) to process routing rules.


List Ingress Resources

kubectl get ingress

Short form:

kubectl get ing

Across all namespaces:

kubectl get ingress -A

Describe an Ingress

kubectl describe ingress frontend

Useful information includes:

  • Host rules
  • Path mappings
  • Backend Services
  • TLS configuration
  • Events

View YAML

kubectl get ingress frontend \
-o yaml

Apply an Ingress Manifest

kubectl apply \
-f ingress.yaml

Delete an Ingress

kubectl delete ingress frontend

Verify Backend Services

kubectl get svc

Ensure the Services referenced by the Ingress exist and expose the expected ports.


Check Controller Pods

For example, if using the NGINX Ingress Controller:

kubectl get pods \
-n ingress-nginx

Troubleshooting Workflow

When traffic does not reach an application, verify:

  1. The Ingress resource exists.
  2. The Ingress Controller is running.
  3. Backend Services are healthy.
  4. Service selectors match Pods.
  5. Pods are Ready.
  6. DNS records point to the Ingress endpoint.
  7. TLS certificates are valid.

Production Best Practices

  • Terminate TLS using trusted certificates.
  • Use host-based routing instead of exposing multiple LoadBalancer Services whenever practical.
  • Apply least-privilege RBAC to Ingress Controller components.
  • Monitor controller logs during routing issues.
  • Validate manifests before deployment using:
kubectl apply \
--dry-run=server \
-f ingress.yaml
  • Consider adopting the Kubernetes Gateway API for new deployments where supported, while continuing to manage existing Ingress resources where appropriate. The Gateway API provides a more expressive and extensible model for traffic management and is increasingly adopted across the Kubernetes ecosystem.

Storage (Persistent Volumes & Persistent Volume Claims)

Containers are designed to be ephemeral, which means data stored inside a container's writable filesystem is lost when the container is deleted or recreated. Kubernetes addresses this limitation through Persistent Volumes (PVs) and Persistent Volume Claims (PVCs).

A Persistent Volume (PV) represents storage provisioned within or outside the cluster, while a Persistent Volume Claim (PVC) is a request for storage made by an application.

Most modern Kubernetes environments use dynamic provisioning through a StorageClass, allowing PVCs to automatically provision storage without requiring administrators to manually create PVs.


List Persistent Volumes

kubectl get pv

Display detailed information:

kubectl describe pv pv-name

List Persistent Volume Claims

kubectl get pvc

Across all namespaces:

kubectl get pvc -A

Describe a PVC:

kubectl describe pvc data-volume

Useful information includes:

  • Capacity
  • Access modes
  • Storage class
  • Bound volume
  • Status
  • Events

View Storage Classes

kubectl get storageclass

Short form:

kubectl get sc

Describe a StorageClass:

kubectl describe storageclass standard

Export Storage Resources

Persistent Volume:

kubectl get pv data-pv -o yaml

Persistent Volume Claim:

kubectl get pvc data-volume -o yaml

Monitor Storage Usage

kubectl get pvc --watch

Verify mounted volumes inside a Pod:

kubectl describe pod database

Delete a PVC

kubectl delete pvc data-volume

Deleting a PVC does not always delete the underlying storage. The behavior depends on the PersistentVolumeReclaimPolicy associated with the bound PV.

Common reclaim policies include:

  • Delete
  • Retain
  • Recycle (legacy; not recommended for new deployments)

Always verify the reclaim policy before deleting production storage resources.


Production Best Practices

  • Prefer dynamic provisioning using StorageClasses.
  • Use StatefulSets for applications requiring persistent storage.
  • Choose access modes appropriate for your workload (ReadWriteOnce, ReadOnlyMany, or ReadWriteMany).
  • Regularly back up critical persistent data.
  • Monitor storage utilization and expansion thresholds.
  • Test disaster recovery and restore procedures periodically.

ConfigMaps

A ConfigMap stores non-sensitive configuration data separately from application code. Separating configuration from container images enables consistent deployments across environments without rebuilding images.

Common use cases include:

  • Environment variables
  • Application configuration files
  • Feature flags
  • Startup parameters
  • Configuration templates

List ConfigMaps

kubectl get configmaps

Short form:

kubectl get cm

Across all namespaces:

kubectl get cm -A

Describe a ConfigMap

kubectl describe configmap app-config

Create a ConfigMap from Literal Values

kubectl create configmap app-config \
--from-literal=ENV=production \
--from-literal=LOG_LEVEL=info

Create from a File

kubectl create configmap app-config \
--from-file=config.yaml

Create from a Directory

kubectl create configmap app-config \
--from-file=./config/

Export a ConfigMap

kubectl get configmap app-config \
-o yaml

Edit a ConfigMap

kubectl edit configmap app-config

Delete a ConfigMap

kubectl delete configmap app-config

Restart Workloads After Configuration Changes

Applications that load configuration only during startup typically require a restart after updating a ConfigMap.

Restart a Deployment:

kubectl rollout restart deployment/frontend

Production Best Practices

  • Store only non-sensitive data in ConfigMaps.
  • Version configuration through GitOps or Infrastructure as Code.
  • Keep ConfigMaps focused on a single application or component.
  • Prefer declarative manifests over imperative creation in production.
  • Avoid embedding large binary files in ConfigMaps.

Secrets

Kubernetes Secrets securely store sensitive information that should not be exposed through ConfigMaps.

Examples include:

  • Database passwords
  • API keys
  • TLS certificates
  • OAuth tokens
  • SSH keys
  • Cloud credentials

Although Secrets are base64 encoded by default, production clusters should also enable encryption at rest and follow strict RBAC policies.


List Secrets

kubectl get secrets

Across all namespaces:

kubectl get secrets -A

Describe a Secret

kubectl describe secret database-secret

Create a Generic Secret

kubectl create secret generic database-secret \
--from-literal=username=dbadmin \
--from-literal=password=StrongPassword123

Create a Secret from Files

kubectl create secret generic tls-secret \
--from-file=tls.crt \
--from-file=tls.key

Create a TLS Secret

kubectl create secret tls website-cert \
--cert=tls.crt \
--key=tls.key

Export Secret Metadata

kubectl get secret database-secret \
-o yaml

Sensitive values remain base64 encoded.


Decode Secret Values

Retrieve a single value:

kubectl get secret database-secret \
-o jsonpath='{.data.password}'

Decode using your operating system's base64 utility if necessary.


Delete a Secret

kubectl delete secret database-secret

Production Best Practices

  • Never store Secrets in source control without encryption.
  • Enable encryption at rest in the Kubernetes API server.
  • Apply least-privilege RBAC policies.
  • Rotate credentials regularly.
  • Use external secret management solutions where appropriate (for example, cloud-native secret managers or HashiCorp Vault integrations).
  • Audit Secret access through Kubernetes audit logging.

Labels & Annotations

Labels and annotations add metadata to Kubernetes resources, but they serve different purposes.

Labels are intended for identifying and selecting resources. They are used by controllers, Services, and selectors.

Annotations store additional metadata that is not used for selection.


Add a Label

kubectl label pod frontend \
environment=production

Overwrite an existing label:

kubectl label pod frontend \
environment=staging \
--overwrite

Remove a Label

kubectl label pod frontend \
environment-

Display Labels

kubectl get pods \
--show-labels

Filter Resources by Label

kubectl get pods \
-l app=frontend

Multiple selectors:

kubectl get pods \
-l app=frontend,environment=production

Add an Annotation

kubectl annotate pod frontend \
owner=platform-team

Overwrite an annotation:

kubectl annotate pod frontend \
owner=operations \
--overwrite

Remove an Annotation

kubectl annotate pod frontend \
owner-

View Resource Metadata

kubectl describe pod frontend

or

kubectl get pod frontend -o yaml

Production Best Practices

  • Establish organization-wide label conventions.
  • Use consistent keys such as app, environment, team, and version.
  • Avoid storing operational data in labels.
  • Reserve annotations for metadata not required by selectors.
  • Keep metadata consistent across all workloads.

Resource Editing

Although declarative workflows are preferred for production environments, kubectl provides several commands for directly inspecting and modifying live resources.

These commands are particularly useful during troubleshooting, testing, and emergency operational changes.


Edit a Resource

kubectl edit deployment frontend

The resource opens in your default terminal editor.


Edit a Service

kubectl edit service frontend

Edit a ConfigMap

kubectl edit configmap app-config

Edit a Secret

kubectl edit secret database-secret

Replace an Entire Resource

kubectl replace -f deployment.yaml

Unlike apply, replace completely replaces the resource definition.


Delete and Recreate

kubectl replace \
--force \
-f deployment.yaml

Use with caution, as this deletes and recreates the resource.


Export Before Editing

Always create a backup before modifying production resources:

kubectl get deployment frontend \
-o yaml > deployment-backup.yaml

Production Best Practices

  • Prefer GitOps workflows for long-term changes.
  • Avoid making permanent production modifications with kubectl edit.
  • Record emergency changes and reconcile them back into version control.
  • Validate manifests before applying them.
  • Review rollout status after configuration changes.

Server-Side Apply

Server-Side Apply (SSA) enables the Kubernetes API server to manage field ownership during declarative updates. Rather than relying solely on client-side state, the API server tracks which workflow or controller owns individual fields.

SSA improves collaboration between automation tools, GitOps platforms, and human operators.


Apply a Manifest

kubectl apply \
-f deployment.yaml

Explicit Server-Side Apply

kubectl apply \
--server-side \
-f deployment.yaml

Specify a Field Manager

kubectl apply \
--server-side \
--field-manager=platform-team \
-f deployment.yaml

Force Ownership

Resolve conflicting ownership when appropriate:

kubectl apply \
--server-side \
--force-conflicts \
-f deployment.yaml

Use this option carefully, as it overrides existing field ownership.


Dry Run Using the API Server

Validate manifests without persisting changes:

kubectl apply \
--server-side \
--dry-run=server \
-f deployment.yaml

Unlike client-side validation, server-side validation checks against the live cluster schema and admission policies.


Production Best Practices

  • Standardize on Server-Side Apply for declarative workflows.
  • Use meaningful field manager names for automation.
  • Validate manifests before applying them.
  • Resolve ownership conflicts intentionally rather than forcing updates by default.
  • Combine Server-Side Apply with GitOps tools for consistent configuration management.
  • Avoid mixing imperative edits with declarative management whenever possible.

Diff

Before applying changes to a cluster, it's often useful to preview what will change. The kubectl diff command compares the live object in the cluster with the local manifest and displays the differences without modifying any resources.

This command is particularly valuable in GitOps workflows, CI/CD pipelines, and change reviews because it reduces the risk of unintended configuration changes.


Compare a Manifest with the Live Resource

kubectl diff -f deployment.yaml

The output highlights additions, removals, and modified fields.


Compare Multiple Manifests

kubectl diff -f ./manifests/

Compare Using Server-Side Apply

kubectl diff \
--server-side \
-f deployment.yaml

This uses the server-side apply engine and more accurately reflects how the API server evaluates the manifest.


Production Best Practices

  • Run kubectl diff before every production deployment.
  • Integrate diff checks into CI/CD pipelines.
  • Review unexpected changes before applying manifests.
  • Combine with GitOps pull request reviews.

Patch

The kubectl patch command updates specific fields of an existing resource without replacing the entire object.

Patching is useful for small operational changes, emergency fixes, and automation scripts.


Patch a Deployment

Update the replica count:

kubectl patch deployment frontend \
-p '{"spec":{"replicas":5}}'

Patch a Service

Modify the Service type:

kubectl patch service frontend \
-p '{"spec":{"type":"LoadBalancer"}}'

Patch a CronJob

Suspend scheduled executions:

kubectl patch cronjob nightly-backup \
-p '{"spec":{"suspend":true}}'

Resume execution:

kubectl patch cronjob nightly-backup \
-p '{"spec":{"suspend":false}}'

Strategic Merge Patch

kubectl patch deployment frontend \
--type=strategic \
-p '{"spec":{"template":{"spec":{"containers":[{"name":"frontend","image":"nginx:1.28"}]}}}}'

JSON Merge Patch

kubectl patch deployment frontend \
--type=merge \
-p '{"spec":{"replicas":3}}'

JSON Patch

kubectl patch deployment frontend \
--type=json \
-p='[
  {
    "op":"replace",
    "path":"/spec/replicas",
    "value":4
  }
]'

Production Best Practices

  • Use patches for small operational updates.
  • Prefer declarative manifests for long-term configuration.
  • Record emergency patches in version control.
  • Test patches in lower environments before production.

Wait

Many automation workflows require waiting for Kubernetes resources to reach a desired state.

The kubectl wait command simplifies scripting by blocking until a specified condition becomes true or a timeout occurs.


Wait for a Pod to Become Ready

kubectl wait \
--for=condition=Ready \
pod/frontend

Wait for Multiple Pods

kubectl wait \
--for=condition=Ready \
pods \
-l app=frontend

Wait for a Deployment

kubectl wait \
deployment/frontend \
--for=condition=Available

Specify a Timeout

kubectl wait \
--for=condition=Ready \
pod/frontend \
--timeout=120s

Wait for Deletion

kubectl wait \
--for=delete \
pod/frontend

Production Best Practices

  • Use kubectl wait in CI/CD pipelines.
  • Always specify appropriate timeouts.
  • Combine with rollout status checks.
  • Avoid relying on arbitrary sleep intervals in automation.

Port Forwarding

The kubectl port-forward command creates a secure tunnel between your local machine and a Pod or Service. It is commonly used for debugging, local development, and accessing internal applications without exposing them externally.


Forward a Local Port to a Pod

kubectl port-forward pod/frontend \
8080:80

Access the application locally:

http://localhost:8080

Forward to a Service

kubectl port-forward service/frontend \
8080:80

Forward Multiple Ports

kubectl port-forward pod/frontend \
8080:80 \
8443:443

Listen on All Interfaces

kubectl port-forward \
--address 0.0.0.0 \
service/frontend \
8080:80

Only use this option on trusted networks, as it exposes the forwarded port beyond localhost.


Stop Port Forwarding

Press:

Ctrl + C

Production Best Practices

  • Prefer port forwarding over temporarily exposing internal services.
  • Restrict forwarded ports to localhost unless explicitly required.
  • Close port-forward sessions after use.
  • Avoid long-running port-forward sessions in production environments.

Copy Files

The kubectl cp command transfers files between your local machine and a container.

It is useful for collecting logs, exporting diagnostic data, importing configuration files, or retrieving generated reports.


Copy a Local File to a Pod

kubectl cp \
config.yaml \
frontend:/etc/config.yaml

Copy a Directory

kubectl cp \
./backup \
frontend:/tmp/

Copy from a Pod

kubectl cp \
frontend:/var/log/app.log \
./app.log

Copy an Entire Directory from a Pod

kubectl cp \
frontend:/var/log \
./logs

Specify a Namespace

kubectl cp \
config.yaml \
production/frontend:/etc/config.yaml

Production Best Practices

  • Use kubectl cp for diagnostics rather than routine file synchronization.
  • Avoid copying sensitive data to unsecured systems.
  • Verify available disk space before transferring large files.
  • Remove temporary files after troubleshooting.

Attach

The kubectl attach command connects your terminal to a running container's primary process. Unlike kubectl exec, it does not start a new process inside the container.

This is useful for observing interactive applications or long-running processes.


Attach to a Pod

kubectl attach frontend

Attach Interactively

kubectl attach \
-it frontend

Attach to a Specific Container

kubectl attach \
-it frontend \
-c nginx

Exit an Attached Session

Detach using the appropriate terminal escape sequence without terminating the containerized process.


Production Best Practices

  • Use attach only when interacting with an application's primary process.
  • Prefer kubectl logs for log inspection.
  • Prefer kubectl exec when a separate shell or command is required.
  • Limit interactive access through RBAC policies.

Exec

The kubectl exec command starts a new process inside a running container. It is one of the most frequently used commands for debugging Kubernetes workloads.

Unlike attach, exec launches an additional command within the container.


Start a Shell

For images with Bash:

kubectl exec \
-it frontend \
-- /bin/bash

For minimal images such as Alpine or BusyBox:

kubectl exec \
-it frontend \
-- /bin/sh

Execute a Single Command

Display environment variables:

kubectl exec frontend \
-- env

List files:

kubectl exec frontend \
-- ls /usr/share/nginx/html

Display the current working directory:

kubectl exec frontend \
-- pwd

Execute Commands in a Specific Container

kubectl exec \
-it frontend \
-c nginx \
-- /bin/sh

Execute Within a Namespace

kubectl exec \
-it frontend \
-n production \
-- /bin/sh

Run Database Commands

Example with PostgreSQL:

kubectl exec \
-it postgres-0 \
-- psql -U postgres

Example with MySQL:

kubectl exec \
-it mysql-0 \
-- mysql -u root -p

Production Troubleshooting Workflow

A common sequence for investigating application issues is:

kubectl get pods

↓

kubectl describe pod

↓

kubectl logs

↓

kubectl logs --previous

↓

kubectl exec

↓

kubectl debug

This progression minimizes disruption while providing increasingly detailed diagnostic information.


Security Considerations

Interactive shell access should be carefully controlled because it provides direct access to running workloads.

Production clusters should:

  • Restrict pods/exec permissions through RBAC.
  • Audit interactive access using Kubernetes audit logs.
  • Avoid performing permanent configuration changes from within containers.
  • Treat containers as immutable and redeploy workloads instead of modifying them manually.

Production Best Practices

  • Use kubectl exec primarily for troubleshooting and diagnostics.
  • Prefer declarative configuration changes over manual in-container edits.
  • Use /bin/sh for lightweight container images that do not include Bash.
  • Exit interactive sessions promptly after completing investigations.
  • Record operational changes and reconcile them back into source-controlled manifests to maintain configuration consistency.

Logging

Logs are one of the first sources of truth when diagnosing Kubernetes application issues. The kubectl logs command retrieves logs directly from containers, making it an essential tool for debugging deployments, monitoring application behavior, and investigating production incidents.

Remember that kubectl logs retrieves logs stored by the container runtime. Long-term log retention should be handled by centralized logging solutions such as Elasticsearch/OpenSearch, Loki, Splunk, Cloud Logging, or other observability platforms.


View Container Logs

Retrieve logs from a single-container Pod:

kubectl logs frontend-7d9b8d8d6f-abcde

Stream Logs

Follow logs in real time:

kubectl logs -f frontend-7d9b8d8d6f-abcde

This is similar to:

tail -f

View Logs from a Specific Container

For Pods containing multiple containers:

kubectl logs frontend \
-c nginx

Retrieve Previous Logs

If a container has restarted, inspect logs from the previous instance:

kubectl logs \
--previous \
frontend

This command is extremely useful when diagnosing:

  • CrashLoopBackOff
  • OOMKilled
  • Startup failures

Display Recent Logs

Retrieve only the last 100 lines:

kubectl logs frontend \
--tail=100

View Logs Since a Duration

kubectl logs frontend \
--since=30m

View Logs Since a Timestamp

kubectl logs frontend \
--since-time=2026-07-31T09:00:00Z

Retrieve Logs from All Containers

kubectl logs frontend \
--all-containers=true

Stream Logs from Multiple Pods

For Deployments:

kubectl logs deployment/frontend

This automatically selects one of the Pods managed by the Deployment.


Retrieve Logs by Label

kubectl logs \
-l app=frontend

Production Logging Best Practices

  • Centralize logs using a dedicated logging platform.
  • Configure log retention policies.
  • Avoid storing sensitive information in logs.
  • Use structured JSON logging where possible.
  • Correlate logs with metrics and traces.
  • Monitor container restart counts.

Debugging

Effective Kubernetes troubleshooting follows a structured workflow. Rather than immediately restarting workloads, engineers typically gather information from multiple sources before making changes.

A common production troubleshooting workflow looks like this:

kubectl get pods

↓

kubectl describe pod

↓

kubectl logs

↓

kubectl logs --previous

↓

kubectl exec

↓

kubectl debug

Inspect Resource Status

List workloads:

kubectl get pods

View detailed information:

kubectl describe pod frontend

Inspect Events

Cluster events often reveal scheduling and runtime problems:

kubectl get events \
--sort-by=.metadata.creationTimestamp

Watch events live:

kubectl get events --watch

Identify Failed Pods

List Pods with status information:

kubectl get pods

Typical error states include:

  • CrashLoopBackOff
  • ImagePullBackOff
  • ErrImagePull
  • Pending
  • OOMKilled
  • CreateContainerConfigError

Inspect Resource Usage

If the Metrics Server is installed:

kubectl top pods

Node metrics:

kubectl top nodes

Inspect Resource Definitions

kubectl get deployment frontend \
-o yaml

Useful when verifying:

  • Labels
  • Environment variables
  • Image versions
  • Volume mounts
  • Resource limits

Investigate Scheduling Failures

kubectl describe pod frontend

Review the Events section for messages such as:

  • Insufficient CPU
  • Insufficient memory
  • Untolerated taints
  • Unsatisfied affinity rules
  • Missing PersistentVolumeClaims

Debug Network Connectivity

Verify Services:

kubectl get svc

Inspect Endpoints:

kubectl get endpoints

Check DNS from within a Pod:

kubectl exec \
-it frontend \
-- nslookup kubernetes.default

Production Debugging Best Practices

  • Gather evidence before restarting workloads.
  • Inspect Events before modifying resources.
  • Compare desired and current state.
  • Preserve failed Pods when possible for investigation.
  • Record findings in incident documentation.

Ephemeral Containers

Ephemeral Containers provide a powerful debugging mechanism for running Pods without modifying the original workload.

Instead of rebuilding application images to include debugging tools, an engineer can temporarily inject a debugging container into an existing Pod.

This approach is particularly useful when production images are intentionally minimal.

Examples include:

  • Distroless images
  • Scratch images
  • Minimal Alpine containers

Start an Ephemeral Debug Container

kubectl debug \
frontend \
-it \
--image=busybox

This launches a temporary BusyBox container within the existing Pod.


Use Ubuntu as a Debug Image

kubectl debug \
frontend \
-it \
--image=ubuntu

Debug a Node

Launch a debugging Pod on a specific node:

kubectl debug node/worker-01 \
-it \
--image=ubuntu

This creates a privileged troubleshooting environment attached to the node.


Verify Ephemeral Containers

kubectl describe pod frontend

Review the Ephemeral Containers section.


When to Use Ephemeral Containers

They are ideal for:

  • Network troubleshooting
  • File system inspection
  • DNS testing
  • Process inspection
  • Connectivity verification
  • Incident response

Production Best Practices

  • Restrict ephemeral container creation through RBAC.
  • Remove debugging sessions promptly.
  • Use trusted debugging images.
  • Audit all debugging activity.
  • Avoid installing tools permanently into application containers.

Rollouts

Deployments, DaemonSets, and StatefulSets support controlled application updates known as rollouts.

Rather than replacing every Pod simultaneously, Kubernetes performs gradual updates to reduce downtime and minimize deployment risk.


Monitor Rollout Progress

kubectl rollout status deployment/frontend

The command blocks until the rollout completes or fails.


View Rollout History

kubectl rollout history deployment/frontend

Inspect a specific revision:

kubectl rollout history deployment/frontend \
--revision=3

Restart a Deployment

Restart Pods without modifying the manifest:

kubectl rollout restart deployment/frontend

This is commonly used after:

  • Updating ConfigMaps
  • Updating Secrets
  • Refreshing environment variables
  • Recovering from transient issues

Pause a Rollout

kubectl rollout pause deployment/frontend

Useful during staged deployments or when validating intermediate changes.


Resume a Rollout

kubectl rollout resume deployment/frontend

Roll Back to the Previous Revision

kubectl rollout undo deployment/frontend

Roll Back to a Specific Revision

kubectl rollout undo deployment/frontend \
--to-revision=2

Monitor StatefulSet Rollouts

kubectl rollout status statefulset/mysql

Monitor DaemonSet Rollouts

kubectl rollout status daemonset/fluent-bit

Verify Updated Images

kubectl get pods \
-o wide

or

kubectl describe deployment frontend

Confirm that new Pods are running the expected container image.


Common Rollout Issues

Typical rollout failures include:

  • Image pull errors
  • Failed readiness probes
  • Failed liveness probes
  • Insufficient cluster resources
  • Scheduling failures
  • Invalid configuration
  • Failed startup commands

The kubectl describe command and Kubernetes Events are usually the fastest way to identify the root cause.


Production Rollout Best Practices

  • Always monitor rollout progress after deployment.
  • Configure readiness probes before liveness probes.
  • Use rolling updates for stateless workloads.
  • Validate changes in lower environments before production.
  • Roll back promptly if health checks fail.
  • Keep Deployment manifests under version control.
  • Automate rollout verification within CI/CD pipelines.

Node Administration

Worker nodes provide the compute capacity that runs Kubernetes workloads. While the control plane manages scheduling and orchestration, cluster administrators frequently use kubectl to inspect node health, manage scheduling, and perform maintenance.

Routine node administration includes:

  • Monitoring node health
  • Draining nodes before maintenance
  • Cordoning and uncordoning nodes
  • Managing taints and labels
  • Inspecting allocatable resources
  • Troubleshooting node failures

List Nodes

kubectl get nodes

Short form:

kubectl get no

Display additional information:

kubectl get nodes -o wide

This shows:

  • Internal IP
  • OS image
  • Kernel version
  • Container runtime
  • Kubernetes version
  • Scheduling status

Describe a Node

kubectl describe node worker-01

Useful information includes:

  • Capacity
  • Allocatable resources
  • Labels
  • Taints
  • Running Pods
  • Node conditions
  • Events

Monitor Node Status

kubectl get nodes --watch

Cordon a Node

Prevent new Pods from being scheduled:

kubectl cordon worker-01

Existing workloads continue running.


Uncordon a Node

Allow scheduling again:

kubectl uncordon worker-01

Drain a Node

Safely evict workloads before maintenance:

kubectl drain worker-01 \
--ignore-daemonsets

Drain while deleting temporary local storage:

kubectl drain worker-01 \
--ignore-daemonsets \
--delete-emptydir-data

Draining respects PodDisruptionBudgets where configured.


View Node Labels

kubectl get nodes \
--show-labels

Label a Node

kubectl label node worker-01 \
node-role.kubernetes.io/gpu=true

Remove a Label

kubectl label node worker-01 \
node-role.kubernetes.io/gpu-

View Node Taints

kubectl describe node worker-01

Review the Taints section.


Add a Taint

kubectl taint nodes worker-01 \
dedicated=database:NoSchedule

Remove a Taint

kubectl taint nodes worker-01 \
dedicated:NoSchedule-

Production Best Practices

  • Drain nodes before OS or Kubernetes upgrades.
  • Avoid deleting nodes before workloads are safely migrated.
  • Use taints to reserve specialized hardware.
  • Label nodes consistently for scheduling policies.
  • Monitor disk, CPU, and memory utilization.
  • Investigate NotReady nodes immediately.

Role-Based Access Control (RBAC)

RBAC controls who can perform actions within a Kubernetes cluster. Permissions are granted through Roles or ClusterRoles, which are then assigned to users, groups, or ServiceAccounts via bindings.

Proper RBAC implementation is fundamental to cluster security.


List Roles

kubectl get roles

Across all namespaces:

kubectl get roles -A

List ClusterRoles

kubectl get clusterroles

Describe a Role

kubectl describe role developer

Describe a ClusterRole

kubectl describe clusterrole view

List RoleBindings

kubectl get rolebindings

List ClusterRoleBindings

kubectl get clusterrolebindings

Create a RoleBinding

kubectl create rolebinding \
developer-binding \
--role=developer \
--user=john \
--namespace=development

Create a ClusterRoleBinding

kubectl create clusterrolebinding \
readonly-admin \
--clusterrole=view \
--user=jane

Delete a RoleBinding

kubectl delete rolebinding developer-binding

Verify Permissions

Determine whether the current identity can perform an action:

kubectl auth can-i create deployments

Check another namespace:

kubectl auth can-i get pods \
-n production

Check permissions for a specific ServiceAccount:

kubectl auth can-i \
list secrets \
--as=system:serviceaccount:development:web-app

Production Best Practices

  • Follow the principle of least privilege.
  • Use namespace-scoped Roles whenever possible.
  • Avoid granting cluster-admin broadly.
  • Review RBAC policies regularly.
  • Audit permission changes.
  • Use groups instead of assigning permissions directly to individual users where possible.

Authentication

Before RBAC authorization occurs, Kubernetes must authenticate the requesting user or workload.

Authentication mechanisms vary depending on the Kubernetes distribution and identity provider.

Common methods include:

  • Client certificates
  • OIDC (OpenID Connect)
  • Cloud IAM integrations
  • ServiceAccount tokens
  • External identity providers

Although authentication is largely configured outside kubectl, several commands assist with verification and troubleshooting.


Display Current Context

kubectl config current-context

View Current Configuration

kubectl config view

Display Active User

kubectl config view --minify

View Available Contexts

kubectl config get-contexts

Switch Context

kubectl config use-context production

Test API Connectivity

kubectl cluster-info

Verify API Access

kubectl auth can-i get pods

Troubleshoot Authentication Issues

Common authentication failures include:

  • Expired credentials
  • Invalid client certificates
  • Incorrect kubeconfig
  • Expired cloud authentication tokens
  • Missing ServiceAccount permissions
  • Incorrect identity provider configuration

Production Best Practices

  • Integrate with enterprise identity providers.
  • Enable multi-factor authentication where supported.
  • Rotate credentials regularly.
  • Encrypt kubeconfig files.
  • Avoid sharing administrative credentials.
  • Remove unused identities promptly.

Metrics

Metrics provide insight into resource consumption and cluster health.

The kubectl top commands rely on the Metrics Server being installed and functioning correctly.

Without Metrics Server, these commands will not return resource usage.


View Node Metrics

kubectl top nodes

Displays:

  • CPU usage
  • CPU percentage
  • Memory usage
  • Memory percentage

View Pod Metrics

kubectl top pods

View Metrics Across Namespaces

kubectl top pods -A

Sort by CPU

kubectl top pods \
--sort-by=cpu

Sort by Memory

kubectl top pods \
--sort-by=memory

View Container Resource Requests

kubectl describe pod frontend

Inspect:

  • Requests
  • Limits
  • QoS class

Export Metrics

For automation:

kubectl top pods \
--no-headers

Production Best Practices

  • Install and maintain Metrics Server.
  • Monitor CPU and memory trends.
  • Right-size resource requests and limits.
  • Alert on sustained resource saturation.
  • Integrate metrics with Prometheus and Grafana for long-term observability.

Performance Tuning

Efficient Kubernetes clusters depend on proper workload configuration, scheduling, and resource management.

Performance tuning is an ongoing process that combines application optimization with Kubernetes best practices.


Inspect Resource Requests and Limits

kubectl describe pod frontend

Review:

  • CPU requests
  • CPU limits
  • Memory requests
  • Memory limits

Monitor Resource Consumption

kubectl top pods

Compare actual usage with configured requests and limits to identify overprovisioned or underprovisioned workloads.


Identify Restarting Pods

kubectl get pods

High restart counts may indicate:

  • Memory exhaustion
  • Probe failures
  • Application crashes
  • Configuration errors

Inspect Node Resource Allocation

kubectl describe node worker-01

Pay particular attention to:

  • Allocatable CPU
  • Allocatable memory
  • Running Pods
  • Resource pressure conditions

Verify Scheduling Constraints

kubectl describe pod frontend

Review scheduling events for:

  • Affinity rules
  • Anti-affinity rules
  • Taints and tolerations
  • Resource availability

Optimize Rollouts

Monitor deployment progress:

kubectl rollout status deployment/frontend

Use rolling updates to minimize downtime during upgrades.


Validate Configuration

Before applying changes:

kubectl apply \
--dry-run=server \
-f deployment.yaml

Production Performance Best Practices

  • Define CPU and memory requests for every workload.
  • Configure appropriate resource limits to prevent noisy-neighbor issues.
  • Use Horizontal Pod Autoscalers (HPA) where applicable.
  • Scale workloads based on observed metrics rather than estimates.
  • Minimize oversized container images to improve startup times.
  • Tune readiness and liveness probes to reflect application behavior.
  • Use anti-affinity rules for highly available applications.
  • Monitor storage latency for stateful workloads.
  • Continuously review resource utilization and adjust requests as workloads evolve.
  • Combine metrics, logs, and traces for comprehensive performance analysis.

Backup & Restore (Production Best Practices)

One of the biggest misconceptions about Kubernetes backups is that running:

kubectl get all -A -o yaml

creates a complete cluster backup.

It does not.

The get all command only exports a limited subset of workload resources. It excludes many important objects, including:

  • Custom Resource Definitions (CRDs)
  • StorageClasses
  • ClusterRoles
  • ClusterRoleBindings
  • Namespaces (in some workflows)
  • Admission configurations
  • Persistent Volume data
  • etcd database contents
  • Cloud-provider resources
  • Some cluster-scoped objects

For disaster recovery, a complete backup strategy should include Kubernetes manifests, cluster-scoped resources, persistent storage, and the underlying control plane state where appropriate.


Export a Deployment

kubectl get deployment frontend \
-o yaml > deployment.yaml

Export a Service

kubectl get service frontend \
-o yaml > service.yaml

Export a ConfigMap

kubectl get configmap app-config \
-o yaml > configmap.yaml

Export a Secret

kubectl get secret database-secret \
-o yaml > secret.yaml

Remember that Secret values remain Base64 encoded and should be handled securely.


Export a Namespace

kubectl get namespace production \
-o yaml

Export Persistent Volume Claims

kubectl get pvc \
-o yaml

Export an Entire Namespace

kubectl get all \
-n production \
-o yaml

This captures common workload resources within the namespace but should not be treated as a complete backup.


Restore Resources

Apply manifests:

kubectl apply \
-f deployment.yaml

Restore an entire directory:

kubectl apply \
-f manifests/

Validate Before Restoring

kubectl apply \
--dry-run=server \
-f deployment.yaml

Verify Restoration

kubectl get all

Inspect workloads:

kubectl describe deployment frontend

Persistent Data Recovery

Restoring Kubernetes manifests does not automatically restore application data.

Persistent storage should be protected using:

  • Storage snapshots
  • CSI snapshot capabilities
  • Cloud-provider volume snapshots
  • Database-native backup tools
  • File-system backups

Disaster Recovery Checklist

A production recovery strategy should include:

  • Kubernetes manifests
  • Cluster-scoped resources
  • Persistent Volumes
  • Storage snapshots
  • Secrets
  • ConfigMaps
  • Git repositories
  • Infrastructure as Code
  • etcd backups (for self-managed control planes)
  • Recovery runbooks
  • Regular recovery testing

Production Best Practices

  • Treat Kubernetes manifests as source-controlled infrastructure.
  • Automate backups.
  • Test restores regularly.
  • Encrypt backup archives.
  • Store backups in multiple locations.
  • Document recovery procedures.

GitOps Workflows

GitOps has become the preferred operational model for managing Kubernetes infrastructure. Rather than making manual changes directly to clusters, engineers store the desired state in version control and use automation to synchronize the cluster.

This approach improves consistency, auditability, and rollback capabilities.


Typical GitOps Workflow

Developer

↓

Git Repository

↓

Pull Request

↓

Review

↓

Merge

↓

GitOps Controller

↓

Kubernetes Cluster

Popular GitOps platforms include:

  • Argo CD
  • Flux

Validate Manifests

kubectl apply \
--dry-run=server \
-f deployment.yaml

Compare Desired State

kubectl diff \
-f deployment.yaml

Apply Declaratively

kubectl apply \
-f deployment.yaml

Export Current State

kubectl get deployment frontend \
-o yaml

Useful when migrating existing workloads into GitOps.


Restart After Configuration Changes

kubectl rollout restart deployment/frontend

Production GitOps Best Practices

  • Treat Git as the single source of truth.
  • Avoid long-term manual edits using kubectl edit.
  • Require pull-request reviews.
  • Use automated policy validation.
  • Sign commits where organizational policies require it.
  • Continuously reconcile cluster state.

CI/CD Usage

Modern CI/CD pipelines frequently interact with Kubernetes through kubectl. Pipelines validate manifests, deploy applications, verify rollouts, and roll back failed releases.

Typical platforms include:

  • GitHub Actions
  • GitLab CI/CD
  • Azure Pipelines
  • Jenkins
  • CircleCI
  • Bitbucket Pipelines

Validate Manifests

kubectl apply \
--dry-run=server \
-f deployment.yaml

Deploy Resources

kubectl apply \
-f deployment.yaml

Deploy an Entire Directory

kubectl apply \
-f manifests/

Monitor Rollout

kubectl rollout status deployment/frontend

Pipelines should wait for successful rollout completion before proceeding.


Verify Resources

kubectl get deployments

Check Pods:

kubectl get pods

Roll Back

kubectl rollout undo deployment/frontend

Example Deployment Flow

Build

↓

Unit Tests

↓

Container Image

↓

Push Registry

↓

kubectl apply

↓

Rollout Status

↓

Smoke Tests

↓

Production

Production CI/CD Best Practices

  • Validate manifests before deployment.
  • Fail pipelines when rollouts fail.
  • Store kubeconfig securely.
  • Use least-privilege ServiceAccounts.
  • Automate rollback procedures.
  • Integrate policy validation into pipelines.

Krew Plugins

Krew is the official plugin manager for kubectl. It extends the command-line interface with community-maintained plugins that simplify common administrative tasks.

Instead of creating custom shell scripts, many engineers rely on Krew plugins for improved productivity.


Verify Plugin Installation

kubectl plugin list

Search for Plugins

kubectl krew search

Install a Plugin

Example:

kubectl krew install ctx

Upgrade Plugins

kubectl krew upgrade

Remove a Plugin

kubectl krew uninstall ctx

Commonly used plugins include:

  • ctx — Switch Kubernetes contexts quickly.
  • ns — Switch namespaces efficiently.
  • tree — Display hierarchical resource relationships.
  • who-can — Identify users or ServiceAccounts with specific permissions.
  • resource-capacity — Analyze cluster resource usage.
  • access-matrix — Visualize RBAC permissions.
  • view-secret — Decode Secret values for authorized users.
  • neat — Simplify exported YAML by removing unnecessary metadata.

Review plugin documentation before installation, as capabilities and maintenance status vary across projects.


Production Best Practices

  • Install plugins only from trusted sources.
  • Review plugin permissions.
  • Keep plugins updated.
  • Standardize plugin usage across engineering teams.
  • Document plugin dependencies in operational runbooks.

Productivity Tips

Experienced Kubernetes administrators rely on several techniques to reduce repetitive typing and improve operational efficiency.


Enable Shell Completion

Bash:

source <(kubectl completion bash)

Zsh:

source <(kubectl completion zsh)

Create a Short Alias

alias k=kubectl

Example:

k get pods

Display Resource Names Only

kubectl get pods \
-o name

Useful for shell pipelines.


Watch Resources Continuously

kubectl get pods \
--watch

Filter by Label

kubectl get pods \
-l app=frontend

Retrieve Wide Output

kubectl get pods \
-o wide

Use JSONPath

Retrieve Pod IPs:

kubectl get pods \
-o jsonpath='{.items[*].status.podIP}'

Export YAML

kubectl get deployment frontend \
-o yaml

Change Namespaces

kubectl config set-context \
--current \
--namespace=production

Verify Current Context

kubectl config current-context

Always confirm the active context before running destructive commands.


Daily Operations Checklist

Before making production changes:

  • Verify the active Kubernetes context.
  • Confirm the current namespace.
  • Validate manifests using server-side dry runs.
  • Review differences with kubectl diff.
  • Monitor rollout progress after deployment.
  • Confirm application health before concluding maintenance.

Productivity Best Practices

  • Use declarative manifests whenever possible.
  • Automate repetitive tasks.
  • Standardize aliases across engineering teams.
  • Prefer labels over manually tracking resource names.
  • Learn keyboard shortcuts and shell completion.
  • Adopt GitOps workflows for long-term configuration management.
  • Build reusable operational runbooks for common administrative tasks.

Common Production Troubleshooting

Production incidents rarely have a single root cause. Effective Kubernetes troubleshooting follows a systematic process that gathers evidence before making changes. Avoid restarting Pods or redeploying applications until you've identified the underlying issue whenever possible.

A recommended investigation flow is:

Check Cluster Health
        ↓
Inspect Nodes
        ↓
Inspect Pods
        ↓
Review Events
        ↓
Check Logs
        ↓
Verify Resources
        ↓
Test Networking
        ↓
Validate Configuration
        ↓
Roll Back (if necessary)

Pods Stuck in Pending

Symptoms:

  • Pods remain in the Pending state.
  • No containers are created.
  • Workloads never start.

Check Pod status:

kubectl get pods

Inspect scheduling events:

kubectl describe pod frontend

Common causes include:

  • Insufficient CPU
  • Insufficient memory
  • Missing PersistentVolumeClaims
  • Node selectors that match no nodes
  • Unsatisfied affinity or anti-affinity rules
  • Untolerated taints
  • Resource quotas
  • Image pull secret issues

Recommended actions:

  • Review Events in kubectl describe.
  • Verify available node capacity.
  • Check resource requests.
  • Confirm PVC availability.
  • Validate scheduling constraints.

CrashLoopBackOff

Symptoms:

  • Containers repeatedly restart.
  • Restart count continuously increases.

View Pod status:

kubectl get pods

Inspect logs:

kubectl logs frontend

Retrieve logs from the previous failed container:

kubectl logs frontend \
--previous

Describe the Pod:

kubectl describe pod frontend

Common causes:

  • Application crashes
  • Invalid configuration
  • Missing environment variables
  • Secret or ConfigMap errors
  • Dependency failures
  • Startup script failures
  • OOMKilled
  • Failed liveness probes

ImagePullBackOff / ErrImagePull

Inspect Pod details:

kubectl describe pod frontend

Verify image name:

kubectl get deployment frontend \
-o yaml

Typical causes:

  • Incorrect image tag
  • Private registry authentication failure
  • Missing imagePullSecrets
  • Registry outage
  • Network connectivity issues

OOMKilled Containers

Inspect Pod details:

kubectl describe pod frontend

View resource usage:

kubectl top pods

Recommended actions:

  • Increase memory limits if appropriate.
  • Investigate application memory leaks.
  • Review JVM or runtime configuration.
  • Optimize application memory consumption.

Failed Readiness Probe

Symptoms:

  • Pod starts successfully.
  • Traffic is never routed to the Pod.

Inspect the Deployment:

kubectl describe deployment frontend

Review probe configuration:

kubectl get deployment frontend \
-o yaml

Verify:

  • Port numbers
  • HTTP paths
  • Startup timing
  • Response codes

Failed Liveness Probe

Symptoms:

  • Containers restart repeatedly.
  • Restart count continues increasing.

Inspect events:

kubectl describe pod frontend

Common causes:

  • Slow startup
  • Incorrect probe path
  • Short timeout
  • Application deadlocks
  • Resource starvation

Node NotReady

Check node status:

kubectl get nodes

Inspect the node:

kubectl describe node worker-01

Common causes:

  • kubelet failure
  • Container runtime issues
  • Network connectivity
  • Disk pressure
  • Memory pressure
  • PID pressure
  • Certificate problems

Service Not Routing Traffic

Verify the Service:

kubectl get svc

Inspect endpoints:

kubectl get endpoints

Verify labels:

kubectl get pods \
--show-labels

Compare labels with the Service selector.


DNS Resolution Problems

Test DNS from inside a Pod:

kubectl exec \
-it frontend \
-- nslookup kubernetes.default

Inspect CoreDNS:

kubectl get pods \
-n kube-system

Review CoreDNS logs:

kubectl logs \
-n kube-system \
deployment/coredns

Persistent Volume Issues

List PVCs:

kubectl get pvc

Describe the claim:

kubectl describe pvc data

Inspect Persistent Volumes:

kubectl get pv

Common causes:

  • StorageClass mismatch
  • Missing provisioner
  • Capacity mismatch
  • Access mode mismatch
  • Pending volume provisioning

Authentication or Authorization Errors

Test permissions:

kubectl auth can-i get pods

Test as another identity:

kubectl auth can-i \
create deployments \
--as=system:serviceaccount:development:web

Inspect bindings:

kubectl get rolebindings

Failed Rollouts

Monitor rollout progress:

kubectl rollout status deployment/frontend

Review rollout history:

kubectl rollout history deployment/frontend

Roll back if necessary:

kubectl rollout undo deployment/frontend

Resource Pressure

View node utilization:

kubectl top nodes

View Pod utilization:

kubectl top pods

Inspect allocatable resources:

kubectl describe node worker-01

Production Incident Checklist

When responding to an incident:

  1. Confirm the affected namespace.
  2. Verify the current Kubernetes context.
  3. Review recent deployments.
  4. Inspect Events.
  5. Check application logs.
  6. Examine previous container logs.
  7. Verify Service endpoints.
  8. Review resource usage.
  9. Confirm node health.
  10. Validate configuration changes.
  11. Roll back only after identifying the cause.
  12. Document findings for future reference.

kubectl Best Practices

While kubectl provides extensive administrative capabilities, following consistent operational practices reduces the risk of accidental outages and improves cluster maintainability.


Prefer Declarative Configuration

Instead of creating resources imperatively:

kubectl create deployment nginx \
--image=nginx

Prefer version-controlled manifests:

kubectl apply \
-f deployment.yaml

Declarative workflows improve reproducibility, auditing, and collaboration.


Use Server-Side Validation

Validate manifests before applying them:

kubectl apply \
--dry-run=server \
-f deployment.yaml

This catches many configuration errors before they reach the cluster.


Review Changes Before Applying

Use:

kubectl diff \
-f deployment.yaml

Reviewing the planned changes helps prevent accidental configuration drift.


Adopt GitOps

Treat Git as the authoritative source for Kubernetes manifests.

Benefits include:

  • Version history
  • Peer review
  • Automated reconciliation
  • Easier rollback
  • Improved auditability

Avoid making long-term configuration changes directly with kubectl edit.


Verify the Active Context

Before modifying production resources:

kubectl config current-context

Many production incidents occur because engineers execute commands against the wrong cluster.


Verify the Active Namespace

Display the current namespace:

kubectl config view --minify

Or specify namespaces explicitly:

kubectl get pods \
-n production

Being explicit reduces the chance of modifying the wrong workload.


Apply the Principle of Least Privilege

Use RBAC to limit permissions.

Verify access:

kubectl auth can-i delete pods

Avoid granting unnecessary administrative privileges.


Label Resources Consistently

Use standardized labels such as:

app: frontend
environment: production
team: platform
version: v2

Consistent labels simplify:

  • Monitoring
  • Logging
  • Scheduling
  • Service selection
  • Automation

Configure Resource Requests and Limits

Every production workload should define:

  • CPU requests
  • CPU limits
  • Memory requests
  • Memory limits

Proper resource configuration improves scheduling and cluster stability.


Configure Health Probes

Use:

  • Startup probes
  • Readiness probes
  • Liveness probes

Well-designed probes improve application availability and reduce unnecessary restarts.


Monitor Rollouts

Always verify deployments:

kubectl rollout status deployment/frontend

Do not assume a deployment completed successfully.


Keep Secrets Out of Git

Never commit plaintext credentials.

Instead:

  • Use Kubernetes Secrets responsibly.
  • Encrypt secrets where possible.
  • Consider external secret management solutions.
  • Restrict RBAC access to Secret resources.

Centralize Observability

Combine:

  • Logs
  • Metrics
  • Traces
  • Kubernetes Events

No single telemetry source provides the complete picture during production incidents.


Use Ephemeral Containers for Debugging

Instead of modifying production images:

kubectl debug frontend \
-it \
--image=busybox

Ephemeral containers reduce risk while providing powerful debugging capabilities.


Regularly Upgrade kubectl

Keep the client version close to the Kubernetes control plane version to maintain compatibility with supported API versions and features.

Verify versions:

kubectl version

Automate Repetitive Tasks

Improve operational consistency through automation:

  • CI/CD pipelines
  • GitOps controllers
  • Shell aliases
  • Krew plugins
  • Infrastructure as Code
  • Policy enforcement

Automation reduces manual errors and increases deployment reliability.


Production Operations Checklist

Before applying changes:

  • Verify the correct Kubernetes context.
  • Confirm the target namespace.
  • Validate manifests with --dry-run=server.
  • Review changes using kubectl diff.
  • Ensure required Secrets and ConfigMaps exist.
  • Confirm resource requests and limits are appropriate.
  • Verify probe configuration.
  • Monitor rollout status after deployment.
  • Validate application health.
  • Record significant operational changes.

Following these practices helps maintain secure, reliable, and predictable Kubernetes environments while reducing operational risk.

100+ Command Quick Reference

The following reference consolidates the most commonly used kubectl commands into a single, searchable section. Commands are grouped by task to make day-to-day cluster administration faster. Replace placeholder names (for example, frontend, production, or worker-01) with values from your own environment.


Cluster Information

kubectl version
kubectl cluster-info
kubectl api-resources
kubectl api-versions
kubectl get componentstatuses
kubectl config view
kubectl config current-context
kubectl config get-contexts
kubectl config use-context production
kubectl config rename-context old new

Namespaces

kubectl get namespaces
kubectl create namespace production
kubectl delete namespace production
kubectl config set-context --current --namespace=production
kubectl get all -n production

Pods

kubectl get pods
kubectl get pods -A
kubectl get pods -o wide
kubectl get pods --show-labels
kubectl describe pod frontend
kubectl delete pod frontend
kubectl logs frontend
kubectl logs -f frontend
kubectl logs --previous frontend
kubectl logs -c nginx frontend
kubectl logs --tail=100 frontend
kubectl logs --since=30m frontend
kubectl exec -it frontend -- sh
kubectl exec -it frontend -- bash
kubectl attach frontend
kubectl cp frontend:/tmp/file ./file
kubectl port-forward pod/frontend 8080:80
kubectl top pods

Deployments

kubectl get deployments
kubectl describe deployment frontend
kubectl create deployment frontend --image=nginx
kubectl scale deployment frontend --replicas=5
kubectl rollout status deployment/frontend
kubectl rollout history deployment/frontend
kubectl rollout restart deployment/frontend
kubectl rollout pause deployment/frontend
kubectl rollout resume deployment/frontend
kubectl rollout undo deployment/frontend
kubectl set image deployment/frontend nginx=nginx:1.30
kubectl delete deployment frontend

ReplicaSets

kubectl get replicasets
kubectl describe replicaset frontend
kubectl delete replicaset frontend

StatefulSets

kubectl get statefulsets
kubectl describe statefulset mysql
kubectl rollout status statefulset/mysql
kubectl rollout restart statefulset/mysql
kubectl delete statefulset mysql

DaemonSets

kubectl get daemonsets
kubectl describe daemonset fluent-bit
kubectl rollout status daemonset/fluent-bit
kubectl rollout restart daemonset/fluent-bit
kubectl delete daemonset fluent-bit

Jobs

kubectl get jobs
kubectl describe job backup
kubectl create job backup --image=busybox
kubectl logs job/backup
kubectl delete job backup

CronJobs

kubectl get cronjobs
kubectl describe cronjob nightly-backup
kubectl create cronjob cleanup --image=busybox --schedule="0 2 * * *"
kubectl patch cronjob cleanup -p '{"spec":{"suspend":true}}'
kubectl delete cronjob cleanup

Services

kubectl get services
kubectl describe service frontend
kubectl expose deployment frontend --port=80
kubectl get endpoints
kubectl delete service frontend

Ingress

kubectl get ingress
kubectl describe ingress frontend
kubectl get ingress -o yaml
kubectl delete ingress frontend

ConfigMaps

kubectl get configmaps
kubectl describe configmap app-config
kubectl create configmap app-config --from-file=config/
kubectl edit configmap app-config
kubectl delete configmap app-config

Secrets

kubectl get secrets
kubectl describe secret database-secret
kubectl create secret generic database-secret
kubectl create secret tls tls-secret --cert=tls.crt --key=tls.key
kubectl get secret database-secret -o yaml
kubectl delete secret database-secret

Persistent Storage

kubectl get pv
kubectl get pvc
kubectl describe pvc data
kubectl describe pv pv-001
kubectl get storageclass
kubectl delete pvc data

Nodes

kubectl get nodes
kubectl get nodes -o wide
kubectl describe node worker-01
kubectl cordon worker-01
kubectl uncordon worker-01
kubectl drain worker-01 --ignore-daemonsets
kubectl top nodes
kubectl label node worker-01 environment=production
kubectl taint node worker-01 dedicated=db:NoSchedule

Labels & Annotations

kubectl label pod frontend app=frontend
kubectl label pod frontend app-
kubectl annotate pod frontend owner=platform
kubectl annotate pod frontend owner-
kubectl get pods -l app=frontend

Resource Management

kubectl apply -f deployment.yaml
kubectl create -f deployment.yaml
kubectl replace -f deployment.yaml
kubectl edit deployment frontend
kubectl delete -f deployment.yaml
kubectl diff -f deployment.yaml
kubectl apply --server-side -f deployment.yaml
kubectl apply --dry-run=server -f deployment.yaml
kubectl patch deployment frontend --patch-file patch.yaml

YAML Output

kubectl get deployment frontend -o yaml
kubectl get service frontend -o yaml
kubectl get pod frontend -o json
kubectl get pods -o wide
kubectl get pods -o name
kubectl get pods -o jsonpath='{.items[*].metadata.name}'

Events

kubectl get events
kubectl get events --sort-by=.metadata.creationTimestamp
kubectl get events --watch

Authentication & RBAC

kubectl auth can-i get pods
kubectl auth can-i create deployments
kubectl auth can-i delete pods --as=user@example.com
kubectl get roles
kubectl get clusterroles
kubectl get rolebindings
kubectl get clusterrolebindings

Metrics

kubectl top pods
kubectl top pods -A
kubectl top pods --sort-by=cpu
kubectl top pods --sort-by=memory
kubectl top nodes

Debugging

kubectl describe pod frontend
kubectl logs frontend
kubectl logs --previous frontend
kubectl exec -it frontend -- sh
kubectl debug frontend -it --image=busybox
kubectl debug node/worker-01 -it --image=ubuntu
kubectl get events
kubectl get endpoints
kubectl describe node worker-01

Rollouts

kubectl rollout status deployment/frontend
kubectl rollout history deployment/frontend
kubectl rollout history deployment/frontend --revision=2
kubectl rollout restart deployment/frontend
kubectl rollout pause deployment/frontend
kubectl rollout resume deployment/frontend
kubectl rollout undo deployment/frontend
kubectl rollout undo deployment/frontend --to-revision=2

Scaling

kubectl scale deployment frontend --replicas=3
kubectl autoscale deployment frontend --cpu-percent=70 --min=2 --max=10

Watching Resources

kubectl get pods --watch
kubectl get deployments --watch
kubectl get services --watch
kubectl get nodes --watch

File Operations

kubectl cp frontend:/etc/nginx/nginx.conf .
kubectl cp ./config.yaml frontend:/tmp/config.yaml

Export Resources

kubectl get deployment frontend -o yaml > deployment.yaml
kubectl get service frontend -o yaml > service.yaml
kubectl get configmap app-config -o yaml > configmap.yaml
kubectl get secret database-secret -o yaml > secret.yaml
kubectl get pvc -o yaml > pvc.yaml

Plugin Management (Krew)

kubectl plugin list
kubectl krew search
kubectl krew install ctx
kubectl krew install ns
kubectl krew upgrade
kubectl krew uninstall ctx

Helpful Aliases

alias k=kubectl

k get pods
k get nodes
k describe pod frontend
k logs -f frontend
k exec -it frontend -- sh

Daily Operations Checklist

Use this checklist during routine cluster administration:

  • Verify the active context.
  • Confirm the target namespace.
  • Review resource changes with kubectl diff.
  • Validate manifests using --dry-run=server.
  • Apply declarative manifests with kubectl apply.
  • Monitor rollout status after deployment.
  • Check Pod health and Events.
  • Review logs for application errors.
  • Confirm Service endpoints.
  • Verify node health and resource utilization.
  • Ensure ConfigMaps and Secrets are available.
  • Roll back deployments promptly if health checks fail.

Together, the commands in this reference cover well over one hundred of the most frequently used kubectl operations for day-to-day Kubernetes administration, troubleshooting, deployment, and cluster maintenance.

Frequently Asked Questions

What is kubectl?

kubectl is the official command-line interface (CLI) for Kubernetes. It communicates with the Kubernetes API server and allows administrators, developers, and platform engineers to deploy applications, inspect cluster resources, troubleshoot workloads, and manage Kubernetes clusters.


Is kubectl installed on Kubernetes nodes?

Not necessarily.

kubectl is a client application and can be installed on:

  • Developer workstations
  • CI/CD runners
  • Bastion hosts
  • Administrative jump boxes
  • Cloud Shell environments

Worker nodes and control plane nodes do not require kubectl to operate.


How does kubectl communicate with a cluster?

kubectl authenticates using credentials stored in a kubeconfig file and communicates with the Kubernetes API server over HTTPS. Every command ultimately becomes one or more API requests that are authorized through Kubernetes authentication and RBAC.


Where is the kubeconfig file stored?

By default:

Linux and macOS:

~/.kube/config

Windows:

%USERPROFILE%\.kube\config

You can specify an alternate configuration file by setting the KUBECONFIG environment variable or by using the --kubeconfig flag.


What is the difference between kubectl create and kubectl apply?

kubectl create creates a resource once and fails if the resource already exists.

Example:

kubectl create -f deployment.yaml

kubectl apply creates the resource if it does not exist or updates it if it already exists.

Example:

kubectl apply -f deployment.yaml

For declarative infrastructure and GitOps workflows, kubectl apply is generally the preferred approach.


What is Server-Side Apply?

Server-Side Apply shifts merge logic from the client to the Kubernetes API server. It improves field ownership tracking, conflict detection, and collaboration between multiple controllers or teams managing the same resources.

Example:

kubectl apply \
--server-side \
-f deployment.yaml

What is the difference between kubectl edit and kubectl apply?

kubectl edit opens the live resource in your default editor and modifies it directly in the cluster.

kubectl edit deployment frontend

kubectl apply updates resources from version-controlled manifests.

For production environments, declarative manifests managed in Git are generally preferred over direct editing.


When should I use kubectl replace?

Use kubectl replace when you want to completely replace an existing resource definition.

kubectl replace \
-f deployment.yaml

Unlike apply, replace overwrites the existing object rather than merging changes.


How do I validate a manifest before applying it?

Use a server-side dry run:

kubectl apply \
--dry-run=server \
-f deployment.yaml

This validates the manifest against the live API server without creating or modifying resources.


How can I preview configuration changes?

Use:

kubectl diff \
-f deployment.yaml

This compares the desired manifest with the current cluster state and displays the differences before applying them.


How do I view logs from a crashing container?

Current logs:

kubectl logs frontend

Previous container instance:

kubectl logs \
--previous \
frontend

The --previous flag is particularly useful for troubleshooting CrashLoopBackOff errors.


How do I access a running container?

kubectl exec \
-it frontend \
-- sh

If the container includes Bash:

kubectl exec \
-it frontend \
-- bash

What are Ephemeral Containers?

Ephemeral Containers are temporary debugging containers injected into an existing Pod without modifying the application's container image.

Example:

kubectl debug \
frontend \
-it \
--image=busybox

They are especially useful for troubleshooting minimal container images that lack debugging utilities.


How do I restart a Deployment?

kubectl rollout restart deployment/frontend

This recreates the Pods managed by the Deployment while preserving the Deployment configuration.


How do I roll back a failed deployment?

Roll back to the previous revision:

kubectl rollout undo deployment/frontend

Roll back to a specific revision:

kubectl rollout undo deployment/frontend \
--to-revision=2

How do I determine whether I have permission to perform an action?

Use:

kubectl auth can-i delete pods

To test another identity:

kubectl auth can-i \
create deployments \
--as=system:serviceaccount:development:web

How do I check CPU and memory usage?

Node metrics:

kubectl top nodes

Pod metrics:

kubectl top pods

These commands require the Metrics Server to be installed.


How do I safely perform node maintenance?

Prevent new scheduling:

kubectl cordon worker-01

Evict workloads:

kubectl drain worker-01 \
--ignore-daemonsets

Return the node to service:

kubectl uncordon worker-01

Does kubectl back up an entire cluster?

No.

While kubectl can export Kubernetes manifests, it does not create a complete disaster recovery backup. A comprehensive backup strategy should also include:

  • Persistent Volume data
  • Storage snapshots
  • Cluster-scoped resources
  • Secrets
  • Infrastructure as Code
  • etcd backups (for self-managed control planes)
  • Recovery documentation and testing

For production environments:

  • Store manifests in Git.
  • Use declarative configuration.
  • Validate changes with server-side dry runs.
  • Preview changes using kubectl diff.
  • Automate deployments with CI/CD.
  • Adopt GitOps reconciliation.
  • Monitor rollout status after every deployment.

This approach improves consistency, security, and auditability.


Conclusion

kubectl remains the primary interface for interacting with Kubernetes, regardless of whether clusters are managed on-premises or through cloud providers. Although higher-level platforms such as GitOps controllers, CI/CD systems, and Kubernetes dashboards automate many operational tasks, they ultimately interact with the same Kubernetes API that kubectl exposes.

Mastering kubectl provides a strong foundation for deploying applications, operating production clusters, investigating incidents, and automating infrastructure workflows. Understanding not only individual commands but also the principles behind declarative configuration, RBAC, rollouts, resource management, and observability enables teams to operate Kubernetes environments more safely and efficiently.

As Kubernetes continues to evolve, operational best practices increasingly emphasize:

  • Declarative resource management
  • GitOps workflows
  • Least-privilege access through RBAC
  • Automated validation and policy enforcement
  • Continuous monitoring and observability
  • Reliable backup and disaster recovery processes
  • Incremental, monitored deployments
  • Infrastructure as Code

Rather than memorizing every available command, focus on understanding the workflows that combine them. Commands such as kubectl apply, kubectl diff, kubectl rollout, kubectl logs, kubectl describe, kubectl top, and kubectl auth can-i form the core toolkit used during everyday cluster administration.

Keep this cheat sheet as a practical reference for day-to-day operations, incident response, and production deployments. As new Kubernetes releases introduce features and APIs, revisit your tooling, validate deprecated commands, and align operational practices with current Kubernetes recommendations to maintain secure, reliable, and maintainable clusters.

Free Engineering ToolsNEW

8 free, 100% client-side tools for developers — no signup, no data uploads.

Explore all tools