Essential kubectl Command Reference for Kubernetes Administration
Configuring Shell Autocompletion
Enabling command completion improves efficiency when working with the CLI. Ensure the appropriate completion package is installed for your shell environment.
# Enable autocomplete for Bash
$ source <(kubectl completion bash)
# Enable autocomplete for Zsh
$ source <(kubectl completion zsh)
Cluster Configuration and Contexts
Manage kubeconfig files to switch between clusters and modify authentication details. Multiple configuration files can be merged for flexible access control.
# Display the merged kubeconfig settings
$ kubectl config view
# Merge multiple config files and view the result
$ KUBECONFIG=~/.kube/config:~/.kube/secondary-config kubectl config view
# Extract the password for a specific user entry
$ kubectl config view -o jsonpath='{.users[?(@.name == "admin")].user.password}'
# Show the active context
$ kubectl config current-context
# Switch the default context to a specific cluster
$ kubectl config use-context production-cluster-01
# Add a new cluster user with basic auth credentials
$ kubectl config set-credentials dev-user --username=developer --password=securepass
# Define a context with a specific user and namespace
$ kubectl config set-context dev-env --user=developer --namespace=development \
&& kubectl config use-context dev-env
Resource Creation
Kubernetes manifests support both YAML and JSON formats. Files typically use .yaml, .yml, or .json extensions.
# Instantiate resources from a manifest file
$ kubectl create -f ./application-manifest.yaml
# Create resources using multiple definition files
$ kubectl create -f ./config.yaml -f ./deployment.yaml
# Recursively create resources from all manifests in a directory
$ kubectl create -f ./manifests/
# Create resources directly from a remote URL
$ kubectl create -f https://raw.githubusercontent.com/repo/main/deploy.yaml
# Launch a simple Nginx instance
$ kubectl run web-server --image=nginx:alpine
# Retrieve documentation for specific resource types
$ kubectl explain pods,services
# Create multiple objects from standard input
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: debug-sleep-long
spec:
containers:
- name: debug
image: busybox
args:
- sleep
- "3600"
---
apiVersion: v1
kind: Pod
metadata:
name: debug-sleep-short
spec:
containers:
- name: debug
image: busybox
args:
- sleep
- "60"
EOF
# Generate a Secret containing encoded credentials
$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Secret
metadata:
name: db-credentials
type: Opaque
data:
password: $(echo "dbpass123" | base64)
username: $(echo "dbadmin" | base64)
EOF
Resource Discvoery and Inspection
Retrieve and filter cluster objects using various output formats and selectors.
# List all services across every namespace
$ kubectl get services --all-namespaces
# List all pods in the current namespace
$ kubectl get pods
# Display pods with extended information including node assignment
$ kubectl get pods -o wide
# Retrieve a specific deployment configuration
$ kubectl get deployment web-backend
# Include uninitialized objects in the pod list
$ kubectl get pods --include-uninitialized
# Show detailed status information for nodes and pods
$ kubectl describe nodes worker-01
$ kubectl describe pods app-pod-123
# Sort services alphabetically by name
$ kubectl get services --sort-by=.metadata.name
# Order pods based on container restart count
$ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
# Extract version labels from pods matching a specific selector
$ kubectl get pods --selector=app=backend -o \
jsonpath='{.items[*].metadata.labels.version}'
# Retrieve External IP addresses for all nodes
$ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
# Find pod names associated with a specific ReplicationController using jq
$ sel=${$(kubectl get rc web-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
$ echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})
# Filter nodes that are in a Ready state
$ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' \
&& kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
# Identify Secrets referenced by containers in current Pods
$ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq
Resource Modification and Updates
Apply changes to existing objects using rolling updates, replacements, or exposure commands.
# Perform a rolling update using a new configuration file
$ kubectl rollout undo deployment/frontend-v1
# Update the container image for a deployment
$ kubectl set image deployment/frontend web-container=nginx:1.21
# Update image specifically for the frontend deployment
$ kubectl set image deployment/frontend web-container=nginx:1.22
# Rollback a deployment to the previous revision
$ kubectl rollout undo deployment/frontend
# Replace a pod definition using stdin JSON
$ cat pod-def.json | kubectl replace -f -
# Force replacement by deleting and recreating the resource (causes downtime)
$ kubectl replace --force -f ./pod-def.json
# Expose a ReplicationController as a Service
$ kubectl expose rc web-server --port=80 --target-port=8080
# Update a pod image version using sed and replace
$ kubectl get pod app-pod -o yaml | sed 's/\(image: myapp\):.*$/\1:v2/' | kubectl replace -f -
# Apply a new label to a pod
$ kubectl label pods app-pod environment=production
# Add an annotation to a pod
$ kubectl annotate pods app-pod description="Critical service"
# Configure horizontal pod autoscaling for a deployment
$ kubectl autoscale deployment web-backend --min=3 --max=15
Patching Strategies
Apply partial updates to resources using strategic merge or JSON patches.
# Mark a node as unschedulable
kubectl patch node worker-02 -p '{"spec":{"unschedulable":true}}'
# Update a container image within a pod spec
$ kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"app-container","image":"updated-image"}]}}'
# Use JSON patch format to modify container image
$ kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new-image"}]'
# Remove liveness probe configuration from a deployment using JSON patch
$ kubectl patch deployment web-app --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'
Interactive Editing
Modify resource definitions directly using the default system editor.
# Edit the configuration of a specific service
$ kubectl edit svc/web-service
# Specify a different text editor for the session
$ KUBE_EDITOR="nano" kubectl edit svc/web-service
Scaling Operations
Adjust the number of replicas for controllers dynamically.
# Set replicaset replica count to 5
$ kubectl scale --replicas=5 rs/web-frontend
# Scale resources defined in a YAML file
$ kubectl scale --replicas=5 -f deployment-config.yaml
# Scale a deployment only if current replicas match expected count
$ kubectl scale --current-replicas=3 --replicas=5 deployment/database
# Scale multiple replication controllers simultaneously
$ kubectl scale --replicas=4 rc/service-a rc/service-b rc/service-c
Resource Deletion
Remove objects from the cluster using file definitions, names, or selectors.
# Delete resources defined in a specific file
$ kubectl delete -f ./pod-def.json
# Delete specific pods and services by name
$ kubectl delete pod,service web-pod web-svc
# Remove resources matching a specific label selector
$ kubectl delete pods,services -l app=web-tier
# Delete labeled resources including uninitialized objects
$ kubectl delete pods,services -l app=web-tier --include-uninitialized
# Purge all pods and services within a specific namespace
$ kubectl -n staging delete po,svc --all
Pod Interaction and Debugging
Access logs, execute commands, and forward ports for running containers.
# Retrieve standard output logs from a pod
$ kubectl logs app-pod-1
# Retrieve logs from a specific container within a multi-container pod
$ kubectl logs app-pod-1 -c sidecar-container
# Stream logs continuously
$ kubectl logs -f app-pod-1
# Stream logs from a specific container
$ kubectl logs -f app-pod-1 -c sidecar-container
# Start an interactive shell session in a new pod
$ kubectl run -i --tty debug-shell --image=busybox -- sh
# Attach to a running container
$ kubectl attach app-pod-1 -i
# Forward local port 5000 to container port 6000
$ kubectl port-forward app-pod-1 5000:6000
# Execute a command inside a single-container pod
$ kubectl exec app-pod-1 -- ls /var/log
# Execute a command inside a specific container of a multi-container pod
$ kubectl exec app-pod-1 -c app-container -- ls /var/log
# Display resource usage metrics for pods and containers
$ kubectl top pod app-pod-1 --containers
Cluster and Node Management
Manage node availability and inspect cluster state.
# Mark a node as unschedulable for maintenance
$ kubectl cordon worker-03
# Safely evict pods from a node for maintenance
$ kubectl drain worker-03
# Mark a node as schedulable again
$ kubectl uncordon worker-03
# Display resource usage metrics for a specific node
$ kubectl top node worker-03
# Display cluster information
$ kubectl cluster-info
# Dump cluster state to standard output
$ kubectl cluster-info dump
# Save cluster state diagnostics to a directory
$ kubectl cluster-info dump --output-directory=/tmp/cluster-diagnostics
# Apply a taint to a node
$ kubectl taint nodes worker-03 dedicated=special-workload:NoSchedule
Imperative Configuration Commands
Configure specific fields on resources using the set subcommand.
Setting Resource Limits
Define CPU and memory requests and limits for containers within controllers.
# Set CPU and memory limits for a specific container in a deployment
$ kubectl set resources deployment web-app -c=nginx --limits=cpu=500m,memory=1Gi
# Configure both requests and limits for all containers in a deployment
$ kubectl set resources deployment web-app --limits=cpu=500m,memory=1Gi --requests=cpu=250m,memory=512Mi
# Remove resource constraints from a deployment
$ kubectl set resources deployment web-app --limits=cpu=0,memory=0 --requests=cpu=0,memory=0
Setting Selectors
Update the label selector for a service. Note that this operation is primarily supported for Service objects.
Setting Images
Update container images for various resource types imperatively.
# Update specific container images in a deployment
$ kubectl set image deployment/web-app nginx=nginx:1.20 busybox=busybox:1.33
# Update images across all deployments and replication controllers
$ kubectl set image deployments,rc nginx=nginx:1.20 --all
# Update all containers in a daemonset to a new image
$ kubectl set image daemonset/logging-agent *=fluentd:latest
# Preview image update changes from a local file without applying
$ kubectl set image -f ./deploy.yaml nginx=nginx:1.20 --local -o yaml
Resource Type Aliases
Common Kubernetes resource types and their shorthand abbreviations.
| Resource Type | Short Name |
|---|---|
| clusters | |
| componentstatuses | cs |
| configmaps | cm |
| daemonsets | ds |
| deployments | deploy |
| endpoints | ep |
| events | ev |
| horizontalpodautoscalers | hpa |
| engresses | ing |
| jobs | |
| limitranges | limits |
| namespaces | ns |
| networkpolicies | |
| nodes | no |
| statefulsets | sts |
| persistentvolumeclaims | pvc |
| persistentvolumes | pv |
| pods | po |
| podsecuritypolicies | psp |
| replicasets | rs |
| replicationcontrollers | rc |
| resourcequotas | quota |
| secrets | |
| serviceaccounts | sa |
| services | svc |
Output Formatting
Customize command output using the -o flag.
| Output Format | Description |
|---|---|
-o=custom-columns=<spec> |
Print table using comma-separated custom columns |
-o=custom-columns-file=<filename> |
Print table using custom column template from file |
-o=json |
Output API object in JSON format |
-o=jsonpath=<template> |
Print fields defined by jsonpath expression |
-o=jsonpath-file=<filename> |
Print fields defined by jsonpath expression in file |
-o=name |
Print only the resource name |
-o=wide |
Output in plain text with additional columns (e.g., node name) |
-o=yaml |
Output API object in YAML format |
Logging Verbosity and Debugging
Control the detail level of CLI output using the -v flag followed by an integer.
| Verbosity Level | Description |
|---|---|
--v=0 |
Always visible to operators. |
--v=1 |
Default reasonable log level for standard use. |
--v=2 |
Extended information about state changes. |
--v=3 |
Debug level detailed output. |
--v=6 |
Display requested resources. |
--v=7 |
Display HTTP request headers. |
--v=8 |
Display HTTP request content. |