06-Exploring-kubectl-commands
KubernetesKubectlDevOpsLocal DevelopmentCLI Beginner 13 min read

06-Exploring-kubectl-commands

Learn what kubectl is, how it works, and master the essential commands, context configuration, aliases, and shortcuts to interact with your Kubernetes cluster efficiently.

Exploring kubectl — Your Kubernetes Command Line Tool

kubectl is your primary interface to a Kubernetes cluster. Whether you are running Minikube locally or managing a production EKS cluster on AWS, almost everything you do with Kubernetes will go through this single binary. This guide covers everything you need to know to become productive with kubectl — from understanding how it works internally to setting up completions and aliases that will save you hours of typing.


1. What Is kubectl and How It Works

Overview

kubectl (pronounced “kube-control”, “kube-c-t-l”, or “kube-cuttle” — all are acceptable) is the official command-line tool for Kubernetes. It allows you to:

  • Deploy and manage applications on a cluster
  • Inspect and describe cluster resources
  • View logs and debug running containers
  • Manage cluster configuration and RBAC
  • Execute commands inside running pods

How kubectl Communicates with the Cluster

kubectl is a REST API client. Every command you run is translated into an HTTP request to the Kubernetes API Server. Here is what happens behind the scenes every time you run a kubectl command:

You → kubectl command
         ↓
   Read kubeconfig (~/.kube/config)
         ↓
   Authenticate (token / cert / OIDC)
         ↓
   HTTP Request to API Server (kube-apiserver)
         ↓
   API Server validates & processes request
         ↓
   etcd / Controller / Scheduler act on it
         ↓
   Response returned → kubectl formats output
         ↓
   Printed to your terminal

You can actually see the raw HTTP calls by adding -v=8 or -v=9 to any kubectl command:

kubectl get pods -v=8

This is extremely useful for debugging authentication issues or understanding what the API is actually doing.

The kubeconfig File

kubectl reads cluster connection details from a file called kubeconfig, located by default at:

~/.kube/config        # Linux / macOS
%USERPROFILE%\.kube\config   # Windows

You can override this with the KUBECONFIG environment variable or the --kubeconfig flag:

export KUBECONFIG=/path/to/custom-config.yaml
kubectl get nodes

# Or per-command
kubectl get nodes --kubeconfig=/path/to/custom-config.yaml

The kubeconfig file has three core sections:

SectionPurpose
clustersAPI server endpoint and CA certificate
usersAuthentication credentials (token, cert, OIDC)
contextsNamed pairing of a cluster + user + namespace

A minimal kubeconfig looks like this:

apiVersion: v1
kind: Config
clusters:
  - name: minikube
    cluster:
      server: https://127.0.0.1:8443
      certificate-authority: /home/user/.minikube/ca.crt
users:
  - name: minikube
    user:
      client-certificate: /home/user/.minikube/profiles/minikube/client.crt
      client-key: /home/user/.minikube/profiles/minikube/client.key
contexts:
  - name: minikube
    context:
      cluster: minikube
      user: minikube
      namespace: default
current-context: minikube

2. Basic kubectl Syntax and Structure

Every kubectl command follows a consistent structure:

kubectl [command] [TYPE] [NAME] [flags]
PartDescriptionExample
commandThe action to performget, apply, delete, describe
TYPEResource type (singular, plural, or short form)pod, pods, po
NAMEName of the specific resource (optional)my-pod
flagsAdditional options--namespace, -o yaml

Examples

# Get all pods in the default namespace
kubectl get pods

# Get a specific pod
kubectl get pod my-nginx-pod

# Get pods in a specific namespace
kubectl get pods --namespace kube-system

# Get pods in all namespaces
kubectl get pods --all-namespaces
# or shorthand
kubectl get pods -A

# Get detailed info about a resource
kubectl describe pod my-nginx-pod

# Output in YAML format
kubectl get pod my-nginx-pod -o yaml

# Output in JSON format
kubectl get pod my-nginx-pod -o json

# Custom column output
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName

Resource Type Shortnames

Kubernetes provides short aliases for most resource types. Memorizing these saves a lot of typing:

Full NameShort Name
podspo
servicessvc
deploymentsdeploy
replicasetsrs
statefulsetssts
daemonsetsds
configmapscm
namespacesns
nodesno
persistentvolumespv
persistentvolumeclaimspvc
serviceaccountssa
ingressesing
horizontalpodautoscalershpa
networkpoliciesnetpol

You can always get the full list with:

kubectl api-resources

3. kubectl Commands

This section covers the most important kubectl commands organized by category.

3.1 Getting & Inspecting Resources

# List resources
kubectl get <resource>
kubectl get pods
kubectl get svc
kubectl get deploy
kubectl get nodes
kubectl get all                      # shows pods, services, deployments, replicasets

# Watch resources in real time
kubectl get pods -w
kubectl get pods --watch

# Describe a resource (human-readable details + events)
kubectl describe pod <pod-name>
kubectl describe node <node-name>
kubectl describe svc <svc-name>

# Get raw YAML/JSON of a live resource
kubectl get pod <pod-name> -o yaml
kubectl get deploy <deploy-name> -o json

# List available API resources
kubectl api-resources

# Explain a resource's fields (built-in docs)
kubectl explain pod
kubectl explain pod.spec
kubectl explain pod.spec.containers
kubectl explain deployment.spec.strategy

3.2 Creating & Applying Resources

# Apply a manifest file (create or update — idempotent)
kubectl apply -f deployment.yaml

# Apply all YAML files in a directory
kubectl apply -f ./manifests/

# Apply from a URL
kubectl apply -f https://raw.githubusercontent.com/example/repo/main/deploy.yaml

# Create a resource (fails if it already exists)
kubectl create -f pod.yaml

# Imperative resource creation (no YAML needed)
kubectl create deployment nginx-deploy --image=nginx:latest --replicas=3
kubectl create namespace dev
kubectl create configmap app-config --from-literal=ENV=production --from-literal=LOG_LEVEL=info
kubectl create secret generic db-secret --from-literal=password=supersecret
kubectl create serviceaccount my-sa

3.3 Updating Resources

# Edit a live resource in your default editor
kubectl edit deployment nginx-deploy
kubectl edit svc my-service

# Update the image of a container in a deployment
kubectl set image deployment/nginx-deploy nginx=nginx:1.25

# Scale a deployment
kubectl scale deployment nginx-deploy --replicas=5

# Patch a resource (merge patch)
kubectl patch deployment nginx-deploy -p '{"spec":{"replicas":3}}'

# Patch using JSON patch
kubectl patch pod my-pod --type='json' -p='[{"op":"replace","path":"/spec/containers/0/image","value":"nginx:1.25"}]'

# Label a resource
kubectl label pod my-pod environment=production
kubectl label pod my-pod tier=frontend --overwrite

# Annotate a resource
kubectl annotate pod my-pod description="Frontend pod for app v2"

3.4 Deleting Resources

# Delete by name
kubectl delete pod my-pod
kubectl delete deployment nginx-deploy
kubectl delete svc my-service

# Delete from a manifest file
kubectl delete -f deployment.yaml

# Delete all pods in a namespace
kubectl delete pods --all -n dev

# Delete a namespace (WARNING: deletes everything inside it)
kubectl delete namespace dev

# Force delete a stuck pod
kubectl delete pod my-pod --grace-period=0 --force

3.5 Viewing Logs

Logs are one of the most common things you will check when debugging:

# View logs of a pod
kubectl logs my-pod

# Follow (stream) logs in real time
kubectl logs -f my-pod

# View logs of a specific container in a multi-container pod
kubectl logs my-pod -c sidecar-container

# View last N lines of logs
kubectl logs my-pod --tail=100

# View logs from the previous (crashed) container instance
kubectl logs my-pod --previous

# View logs from all pods matching a label selector
kubectl logs -l app=nginx --all-containers=true

3.6 Executing Commands in Pods

# Open an interactive shell in a pod
kubectl exec -it my-pod -- /bin/bash
kubectl exec -it my-pod -- /bin/sh     # for Alpine/minimal images

# Run a single command in a pod
kubectl exec my-pod -- ls /app
kubectl exec my-pod -- cat /etc/nginx/nginx.conf

# Exec into a specific container inside a pod
kubectl exec -it my-pod -c my-container -- /bin/bash

3.7 Port Forwarding

Port forwarding lets you access a service or pod directly from your local machine without exposing it externally:

# Forward local port 8080 → pod port 80
kubectl port-forward pod/my-pod 8080:80

# Forward local port 8080 → service port 80
kubectl port-forward svc/my-service 8080:80

# Forward local port 8080 → deployment port 80
kubectl port-forward deployment/nginx-deploy 8080:80

# Bind to all interfaces (accessible from other machines on your network)
kubectl port-forward svc/my-service 8080:80 --address=0.0.0.0

3.8 Copying Files To/From Pods

# Copy a file from your local machine to a pod
kubectl cp ./config.json my-pod:/app/config.json

# Copy a file from a pod to your local machine
kubectl cp my-pod:/var/log/app.log ./app.log

# Copy from a specific container in a pod
kubectl cp my-pod:/app/data ./data -c my-container

3.9 Managing Rollouts

# Check rollout status of a deployment
kubectl rollout status deployment/nginx-deploy

# View rollout history
kubectl rollout history deployment/nginx-deploy

# View details of a specific revision
kubectl rollout history deployment/nginx-deploy --revision=2

# Rollback to the previous version
kubectl rollout undo deployment/nginx-deploy

# Rollback to a specific revision
kubectl rollout undo deployment/nginx-deploy --to-revision=2

# Pause a rollout
kubectl rollout pause deployment/nginx-deploy

# Resume a paused rollout
kubectl rollout resume deployment/nginx-deploy

3.10 Working with Namespaces

# List all namespaces
kubectl get namespaces

# Create a namespace
kubectl create namespace staging

# Set a default namespace for your current context
kubectl config set-context --current --namespace=staging

# View resources across all namespaces
kubectl get pods -A
kubectl get svc --all-namespaces

3.11 Cluster Information Commands

# Display cluster info
kubectl cluster-info

# List all nodes
kubectl get nodes

# Detailed node info
kubectl describe node <node-name>

# View resource usage (requires metrics-server)
kubectl top nodes
kubectl top pods
kubectl top pods --sort-by=memory
kubectl top pods --sort-by=cpu

# View component status
kubectl get componentstatuses

# Check API server version
kubectl version
kubectl version --short

3.12 Running Temporary Pods (Debugging)

A very common pattern is to spin up a temporary pod just to debug network connectivity or DNS:

# Run a temporary busybox pod
kubectl run debug-pod --image=busybox --rm -it --restart=Never -- /bin/sh

# Run a temporary curl pod
kubectl run curl-test --image=curlimages/curl --rm -it --restart=Never -- sh

# Run an nginx pod and expose it immediately
kubectl run nginx-test --image=nginx --port=80
kubectl expose pod nginx-test --port=80 --type=NodePort

# Debug DNS resolution from inside the cluster
kubectl run dns-test --image=busybox --rm -it --restart=Never -- nslookup kubernetes.default

4. Configuring kubectl Context

A context in Kubernetes is a named combination of a cluster, a user, and a namespace. If you work with multiple clusters (Minikube, EKS, GKE, etc.), contexts let you switch between them instantly.

Viewing Context Information

# Show the current active context
kubectl config current-context

# List all available contexts
kubectl config get-contexts

# View the full kubeconfig
kubectl config view

# View kubeconfig with secrets unredacted
kubectl config view --raw

Switching Contexts

# Switch to a different context
kubectl config use-context minikube
kubectl config use-context my-eks-cluster
kubectl config use-context gke_project_region_cluster

# Example output of get-contexts
# CURRENT   NAME              CLUSTER           AUTHINFO          NAMESPACE
# *         minikube          minikube          minikube          default
#           eks-prod          eks-prod          eks-prod-admin    production
#           gke-staging       gke-staging       gke-user          staging

Modifying Contexts

# Set a namespace for the current context (so you don't have to type -n every time)
kubectl config set-context --current --namespace=dev

# Rename a context
kubectl config rename-context old-name new-name

# Delete a context
kubectl config delete-context my-old-context

# Merge multiple kubeconfig files
export KUBECONFIG=~/.kube/config:~/.kube/eks-config:~/.kube/gke-config
kubectl config view --merge --flatten > ~/.kube/merged-config
export KUBECONFIG=~/.kube/merged-config

Creating a New Context Manually

# Add a new cluster entry
kubectl config set-cluster my-cluster \
  --server=https://my-api-server:6443 \
  --certificate-authority=/path/to/ca.crt

# Add a new user entry
kubectl config set-credentials my-user \
  --client-certificate=/path/to/client.crt \
  --client-key=/path/to/client.key

# Create a context combining the above
kubectl config set-context my-context \
  --cluster=my-cluster \
  --user=my-user \
  --namespace=default

# Activate it
kubectl config use-context my-context

For frequent context and namespace switching, install kubectx and kubens:

# Install on Linux/macOS via brew
brew install kubectx

# Switch context (interactive fuzzy search with fzf)
kubectx

# Switch to a specific context
kubectx minikube

# Switch namespace
kubens dev

# Switch back to previous context
kubectx -

5. kubectl Completion for Bash

Tab completion is a productivity multiplier. Instead of typing full resource names and flags, you press Tab and let the shell complete it for you.

Enable Completion on Linux (Bash)

# Step 1: Ensure bash-completion is installed
sudo apt-get install bash-completion    # Debian/Ubuntu
sudo yum install bash-completion        # RHEL/CentOS/Amazon Linux

# Step 2: Verify it is sourced in your shell
type _init_completion

# Step 3: Generate and source kubectl completion
echo 'source <(kubectl completion bash)' >> ~/.bashrc

# Step 4: Also enable completion for the 'k' alias (if you use it)
echo 'alias k=kubectl' >> ~/.bashrc
echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc

# Step 5: Apply changes
source ~/.bashrc

Enable Completion on macOS (Bash)

macOS ships with an older version of Bash. It is recommended to use Zsh on Mac, but if you prefer Bash:

# Install newer bash and bash-completion
brew install bash bash-completion@2

# Add to ~/.bash_profile
echo '[[ -r "$(brew --prefix)/etc/profile.d/bash_completion.sh" ]] && . "$(brew --prefix)/etc/profile.d/bash_completion.sh"' >> ~/.bash_profile
echo 'source <(kubectl completion bash)' >> ~/.bash_profile
source ~/.bash_profile

Enable Completion for Zsh (macOS and Linux)

# Zsh is default on modern macOS (Catalina+)
echo 'source <(kubectl completion zsh)' >> ~/.zshrc
echo 'alias k=kubectl' >> ~/.zshrc
echo 'compdef __start_kubectl k' >> ~/.zshrc
source ~/.zshrc

Verify Completion Is Working

# Type the following and press Tab
kubectl get po<TAB>          # completes to 'pods'
kubectl get pods <TAB>       # shows pod names
kubectl -n <TAB>             # shows available namespaces
kubectl describe pod <TAB>   # shows running pod names

6. Helpful Aliases and Shortcuts

Typing kubectl hundreds of times a day gets old fast. These aliases and shell functions are commonly used by experienced Kubernetes engineers.

Basic Aliases

Add these to your ~/.bashrc or ~/.zshrc:

# Core alias
alias k='kubectl'

# Get shortcuts
alias kg='kubectl get'
alias kgp='kubectl get pods'
alias kgpa='kubectl get pods -A'
alias kgpw='kubectl get pods -w'
alias kgd='kubectl get deployments'
alias kgs='kubectl get svc'
alias kgn='kubectl get nodes'
alias kgns='kubectl get namespaces'
alias kgcm='kubectl get configmaps'
alias kgsec='kubectl get secrets'
alias kgpv='kubectl get pv'
alias kgpvc='kubectl get pvc'
alias kgall='kubectl get all -A'

# Describe shortcuts
alias kd='kubectl describe'
alias kdp='kubectl describe pod'
alias kdd='kubectl describe deployment'
alias kds='kubectl describe svc'

# Apply/delete shortcuts
alias kaf='kubectl apply -f'
alias kdf='kubectl delete -f'

# Logs shortcut
alias kl='kubectl logs'
alias klf='kubectl logs -f'

# Exec into pod
alias kex='kubectl exec -it'

# Context and namespace shortcuts
alias kctx='kubectl config use-context'
alias kns='kubectl config set-context --current --namespace'
alias kcv='kubectl config view'
alias kcc='kubectl config current-context'
alias kgc='kubectl config get-contexts'

# Namespace shortcuts
alias kdev='kubectl config set-context --current --namespace=dev'
alias kprod='kubectl config set-context --current --namespace=production'
alias kstg='kubectl config set-context --current --namespace=staging'

Power Shell Functions

These are more advanced and let you use arguments:

# Get pods in a namespace quickly
# Usage: kgpn dev
kgpn() { kubectl get pods -n "$1"; }

# Exec into a pod with bash or sh fallback
# Usage: kbash my-pod
kbash() {
  kubectl exec -it "$1" -- /bin/bash 2>/dev/null || \
  kubectl exec -it "$1" -- /bin/sh
}

# Tail logs with optional container name
# Usage: klogs my-pod [container-name]
klogs() {
  if [ -n "$2" ]; then
    kubectl logs -f "$1" -c "$2"
  else
    kubectl logs -f "$1"
  fi
}

# Delete a pod by name (useful when pods are stuck)
# Usage: kdelpod my-pod
kdelpod() {
  kubectl delete pod "$1" --grace-period=0 --force
}

# Watch pod status for a deployment
# Usage: kwatchdeploy nginx-deploy
kwatchdeploy() {
  kubectl rollout status deployment/"$1"
}

# Port forward quickly
# Usage: kpf my-pod 8080:80
kpf() {
  kubectl port-forward pod/"$1" "$2"
}

# Get all resources in a namespace
# Usage: kgetall dev
kgetall() {
  kubectl get all -n "$1"
}

# Switch context and set namespace in one command
# Usage: kswitch minikube default
kswitch() {
  kubectl config use-context "$1"
  kubectl config set-context --current --namespace="${2:-default}"
  echo "Switched to context: $1, namespace: ${2:-default}"
}

Apply Aliases Permanently

# Reload your shell config after adding aliases
source ~/.bashrc    # Bash
source ~/.zshrc     # Zsh

# Or add them to a dedicated file and source it
echo 'source ~/.kubectl_aliases' >> ~/.bashrc

PS1 Prompt — Show Current Context and Namespace

Knowing which cluster you are connected to at a glance prevents accidental commands against production. Add the kube-ps1 tool:

# Install kube-ps1
brew install kube-ps1   # macOS

# For Linux, clone the repo
git clone https://github.com/jonmosco/kube-ps1.git ~/.kube-ps1

# Add to ~/.bashrc
source ~/.kube-ps1/kube-ps1.sh
PS1='$(kube_ps1) \$ '

# Result: your prompt will look like:
# (⎈ |minikube:default) $
# (⎈ |eks-prod:production) $

7. Where to Find the kubectl Documentation

Official Kubernetes Documentation

The primary reference for all things kubectl is the official Kubernetes docs:

ResourceURL
kubectl Overviewhttps://kubernetes.io/docs/reference/kubectl/
kubectl Cheat Sheethttps://kubernetes.io/docs/reference/kubectl/cheatsheet/
kubectl Command Referencehttps://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands
API Referencehttps://kubernetes.io/docs/reference/kubernetes-api/
Conceptshttps://kubernetes.io/docs/concepts/
Tutorialshttps://kubernetes.io/docs/tutorials/

Built-in Help (Most Underused Feature)

kubectl has excellent built-in documentation that works completely offline:

# Top-level help
kubectl help
kubectl --help

# Help for a specific command
kubectl get --help
kubectl apply --help
kubectl rollout --help

# Explain any Kubernetes resource field interactively
kubectl explain pod
kubectl explain pod.spec
kubectl explain pod.spec.containers.resources
kubectl explain deployment.spec.strategy.rollingUpdate

# Very detailed field info with recursion
kubectl explain pod --recursive

kubectl explain is essentially the API reference built into the CLI. When working offline or during exams like the CKA, this is invaluable.

Kubernetes API Reference Online

If you want the full schema of any Kubernetes object:

https://kubernetes.io/docs/reference/kubernetes-api/

For example:

Community Resources

ResourceDescription
kubectl GitHubhttps://github.com/kubernetes/kubectl — source code and issue tracker
Kubernetes Slackhttps://slack.k8s.io — active community, #kubectl and #kubernetes-users channels
kubectl Plugins (krew)https://krew.sigs.k8s.io — plugin manager for kubectl
Awesome kubectl pluginshttps://github.com/ishantanu/awesome-kubectl-plugins