f in x
Advanced kubectl: Essential Commands and Resource Management from CLI for Kubernetes
> cd .. / HUB_EDITORIALE
Analisi dei dati e metriche

Advanced kubectl: Essential Commands and Resource Management from CLI for Kubernetes

[2026-06-07] Author: Ing. Calogero Bono

Managing dozens of namespaces, hundreds of pods, and unresponsive rollouts? The terminal is your best ally, but only if you use kubectl the right way. At Meteora Web, we work on Kubernetes clusters every day, and we've seen how much time is wasted without a clear command strategy. This guide goes beyond kubectl get pods: you'll learn to query, filter, modify, and debug resources with surgical precision.

Context is everything: kubeconfig, namespaces, and aliases

Before running any command, you must know which cluster and namespace you're targeting. The most common mistake is acting on the wrong cluster and accidentally modifying production resources.

Context configuration

kubectl config manages multiple clusters, users, and namespaces. Essential commands:

# Show the active context
kubectl config current-context

# List all available contexts
kubectl config get-contexts

# Switch context (e.g., from staging to production)
kubectl config use-context production

# Set a default namespace for the active context
kubectl config set-context --current --namespace=production

At Meteora Web, we always use kubectl config view to verify certificates and server endpoints, especially after switching cloud providers.

Aliases and autocompletion

Type less, do more. Set up bash/zsh autocompletion and create quick aliases:

# Autocompletion for bash
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc

# Useful aliases
alias k='kubectl'
alias kgp='kubectl get pods'
alias kd='kubectl describe'
alias krm='kubectl delete'
alias ksys='kubectl --namespace=kube-system'

Immediate action: Add these aliases to your profile and enable autocompletion. You save seconds per command, which becomes hours over a year.

Effective queries: selecting, filtering, formatting

kubectl get is the most used command, but most operators use it poorly. Learn to use label selectors, field selectors, and custom output.

Filtering with label selectors

# All pods with label app=nginx and environment=production
kubectl get pods -l app=nginx,env=production

# Pods with any label 'app'
kubectl get pods -l 'app'

# Pods without a specific label
kubectl get pods -l '!tier'

Field selectors

Field selectors work on state properties (e.g., pod phase):

# Pods in 'Running' phase
kubectl get pods --field-selector status.phase=Running

# Pods on a specific node
kubectl get pods --field-selector spec.nodeName=worker-2

Formatted output with custom columns and JSONPath

With dozens of pods, a standard table is useless. Use -o custom-columns to extract only what you need:

# Show pod, namespace, node, and IP
kubectl get pods -o custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace,NODE:.spec.nodeName,IP:.status.podIP

# Same using simple JSONPath
kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.podIP}{"\n"}{end}'

Operational tip: For quick analysis, use kubectl get all -A -o wide to see all resources across all namespaces. But be careful on large clusters — better to limit with --namespace and -l.

Resource management: creating, updating, deleting smartly

Modifying resources directly from the CLI is powerful, but can break the cluster if done wrong. Here are the practices we use.

Creating resources with `kubectl apply` vs `create`

apply is declarative: you write the YAML manifest and apply it; Kubernetes manages the desired state. create is imperative: it creates the resource but doesn't update it. We always use apply for deployments and services.

# Create or update a deployment
kubectl apply -f deployment.yaml

# Create a temporary resource for testing
kubectl create deployment nginx --image=nginx:1.25 --replicas=3 --dry-run=client -o yaml | kubectl apply -f -

Updating existing resources

For quick modifications (e.g., changing an environment variable or replicas):

# Scale replicas to 5 (imperative)
kubectl scale deployment/nginx --replicas=5

# Update image in a deployment
kubectl set image deployment/nginx nginx=nginx:1.26

# Patch a specific field
kubectl patch deployment nginx -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","env":[{"name":"LOG_LEVEL","value":"debug"}]}]}}}}'

Delete with caution

Don't use kubectl delete pod --all in production if pods are managed by a ReplicaSet (they'll be recreated). To delete everything in a namespace:

# Delete all resources except PersistentVolumeClaim
kubectl delete all --all -n dev

# Delete only pods with label 'batch=true'
kubectl delete pod -l batch=true

Advanced debugging: logs, exec, port-forward, and events

When a pod crashes, you need to understand why in seconds.

Interactive logs and tail

# Follow logs in real time from a multi-container pod
kubectl logs -f pod/web-xxx -c sidecar

# Show last 50 lines
kubectl logs --tail=50 pod/web-xxx

# Logs from a previous instance (if pod is in CrashLoopBackOff)
kubectl logs -p pod/web-xxx

Exec into the container

# Interactive shell
kubectl exec -it pod/web-xxx -- /bin/sh

# Run a single command and get output
kubectl exec pod/web-xxx -- ls -la /app

Port-forward for local testing

# Expose a service on localhost:8080
kubectl port-forward service/web-service 8080:80

Describing and getting events

# Detailed resource info
kubectl describe pod web-xxx

# Recent cluster events
kubectl get events --sort-by='.lastTimestamp' -n production | tail -20

Common pitfalls: Forgetting that kubectl logs -p only works if the container is still in a terminated state (not if it has been removed). Use kubectl get events to understand why a pod won't start.

Managing ConfigMap and Secrets safely

Sensitive configuration must be handled carefully. kubectl create secret and kubectl create configmap are the basic commands, but beware of inline values in terminal history.

# Create secret from file (recommended over --from-literal)
kubectl create secret generic db-credentials --from-file=username.txt --from-file=password.txt

# Create configmap from a directory of config files
kubectl create configmap app-config --from-file=config.d/

# View decoded secret (risky but needed)
kubectl get secret db-credentials -o jsonpath='{.data.password}' | base64 --decode

Warning: Do not run kubectl get secret -o yaml in shared environments: base64 data is visible to anyone with cluster access. Use RBAC to restrict.

Rollout and rollback: managing releases

When you update a deployment, kubectl lets you monitor and undo changes.

# Check rollout status
kubectl rollout status deployment/nginx

# Revision history
kubectl rollout history deployment/nginx

# Roll back to the previous stable revision
kubectl rollout undo deployment/nginx

# Roll back to a specific revision (e.g., revision 3)
kubectl rollout undo deployment/nginx --to-revision=3

Tip: Always set progressDeadlineSeconds in your deployments to avoid endless rollouts. Use kubectl rollout pause/resume for canary updates.

In a nutshell — what to do now

  1. Set up your environment: aliases, autocompletion, default namespace per context.
  2. Master label selectors and custom columns: reduce information noise by 90%.
  3. Prefer declarative kubectl apply for all production resources.
  4. Own the debugging commands: logs with flags, describe, events. Don't waste time staring at dashboards.
  5. Never expose secrets in plaintext: use --from-file and RBAC to limit visibility.

The terminal is your most powerful control panel. At Meteora Web, we use it every day to manage Kubernetes clusters on cloud and on-prem. If you want to go deeper into CI/CD integration, check out our guide on GitHub Actions: automatic deployment of YAML manifests to Kubernetes.

Sponsored Protocol

Ing. Calogero Bono

> AUTHOR_EXTRACTED

Ing. Calogero Bono

Co-founder di Meteora Web. Ingegnere informatico, sviluppo ecosistemi digitali ad alte prestazioni. AI, automazione, SEO tecnica e infrastrutture web. Scrivo di tecnologia per rendere complesso… semplice.

[ Read Full Dossier ]

Hai bisogno di applicare questa strategia?

Esegui il protocollo di contatto per iniziare un progetto con noi.

> INIZIA_PROGETTO

Sponsored

> MW_JOURNAL

> READ_ALL()