Master Kubectl in 5 Minutes: Essential Commands for Kubernetes
This guide provides a concise, 5‑minute overview of the most frequently used kubectl commands—including autocomplete setup, context management, resource creation, querying, updating, patching, scaling, and troubleshooting—complete with ready‑to‑run code snippets for efficient Kubernetes cluster operations.
Kubectl is the primary command‑line tool for interacting with Kubernetes clusters, and mastering its most common commands can greatly improve operational efficiency.
Kubectl Autocomplete
# setup autocomplete in bash (requires bash‑completion package)
source <(kubectl completion bash)
# setup autocomplete in zsh
source <(kubectl completion zsh)Kubectl Context and Configuration
# Show merged kubeconfig
kubectl config view
# Use multiple kubeconfig files
KUBECONFIG=~/.kube/config:~/ .kube/kubconfig2 kubectl config view
# Get password for user e2e
kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'
# Show current context
kubectl config current-context
# Set default context
kubectl config use-context my-cluster-name
# Add a new cluster with basic auth
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
# Set context with specific user and namespace
kubectl config set-context gce --user=cluster-admin --namespace=foo && kubectl config use-context gceCreating Resources
Kubernetes manifests can be written in YAML or JSON. Use the following commands to create resources.
# Create a resource from a manifest file
kubectl create -f ./my-manifest.yaml
# Create resources from multiple files
kubectl create -f ./my1.yaml -f ./my2.yaml
# Create all resources in a directory
kubectl create -f ./dir
# Create a resource from a URL
kubectl create -f https://git.io/vPieo
# Run an nginx pod
kubectl run nginx --image=nginx
# Explain API objects
kubectl explain pods,svc
# Create multiple objects from stdin
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Pod
metadata:
name: busybox-sleep
spec:
containers:
- name: busybox
image: busybox
args:
- "sleep"
- "1000000"
---
apiVersion: v1
kind: Pod
metadata:
name: busybox-sleep-less
spec:
containers:
- name: busybox
image: busybox
args:
- "sleep"
- "1000"
EOF
# Create a Secret with key/value pairs
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: $(echo "s33msi4" | base64)
username: $(echo "jane" | base64)
EOFListing and Finding Resources
# List all services in all namespaces
kubectl get services
# List all pods in all namespaces
kubectl get pods --all-namespaces
# List pods with wide output
kubectl get pods -o wide
# Get a specific deployment
kubectl get deployment my-dep
# Include uninitialized pods
kubectl get pods --include-uninitialized
# Describe nodes and pods
kubectl describe nodes my-node
kubectl describe pods my-pod
# List services sorted by name
kubectl get services --sort-by=.metadata.name
# Sort pods by restart count
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
# Get version label of pods with app=cassandra
kubectl get pods --selector=app=cassandra -o jsonpath='{.items[*].metadata.labels.version}'
# Get ExternalIP of all nodes
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
# List pod names belonging to a specific RC using jq
sel=${$(kubectl get rc my-rc --output=json | jq -j '.spec.selector | to_entries | .[] | "\(.key)=\(.value),"')%?}
echo $(kubectl get pods --selector=$sel --output=jsonpath={.items..metadata.name})
# Show ready nodes
JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
# List Secrets used by current pods
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniqUpdating Resources
# Rolling update a pod
kubectl rolling-update frontend-v1 -f frontend-v2.json
# Update image during rolling update
kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2
# Force replace a pod from stdin JSON
cat pod.json | kubectl replace -f -
# Force replace with --force (may cause downtime)
kubectl replace --force -f ./pod.json
# Expose a replication controller as a service
kubectl expose rc nginx --port=80 --target-port=8000
# Patch a pod image using sed and replace
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
# Add a label to a pod
kubectl label pods my-pod new-label=awesome
# Add an annotation to a pod
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq
# Autoscale a deployment
kubectl autoscale deployment foo --min=2 --max=10Patching Resources
Use strategic merge patches or JSON patches to modify resources.
# Patch a node to be unschedulable
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
# Patch a pod container image (strategic merge)
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
# JSON patch to change container image
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'
# JSON patch to remove livenessProbe from a deployment
kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'Editing Resources
# Edit a service named docker-registry
kubectl edit svc/docker-registry
# Use a different editor (nano)
KUBE_EDITOR="nano" kubectl edit svc/docker-registryScaling Resources
# Scale a replicaset to 3 replicas
kubectl scale --replicas=3 rs/foo
# Scale resources defined in a yaml file
kubectl scale --replicas=3 -f foo.yaml
# Scale a deployment from 2 to 3 replicas
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
# Scale multiple replication controllers
kubectl scale --replicas=5 rc/foo rc/bar rc/bazDeleting Resources
# Delete resources defined in pod.json
kubectl delete -f ./pod.json
# Delete a specific pod and service
kubectl delete pod,service baz foo
# Delete resources with a label selector
kubectl delete pods,services -l name=myLabel
# Delete including uninitialized resources
kubectl delete pods,services -l name=myLabel --include-uninitialized
# Delete all pods and services in a namespace
kubectl -n my-ns delete po,svc --allInteracting with Running Pods
# Show pod logs
kubectl logs my-pod
# Show logs of a specific container
kubectl logs my-pod -c my-container
# Stream pod logs
kubectl logs -f my-pod
kubectl logs -f my-pod -c my-container
# Run an interactive shell in a pod
kubectl run -i --tty busybox --image=busybox -- sh
# Attach to a running container
kubectl attach my-pod -i
# Port‑forward pod port 6000 to local 5000
kubectl port-forward my-pod 5000:6000
# Execute a command in a pod (single container)
kubectl exec my-pod -- ls /
# Execute a command in a specific container
kubectl exec my-pod -c my-container -- ls /
# Show resource usage for a pod and its containers
kubectl top pod POD_NAME --containersNode and Cluster Interaction
# Mark a node unschedulable
kubectl cordon my-node
# Drain a node for maintenance
kubectl drain my-node
# Mark a node schedulable again
kubectl uncordon my-node
# Show node metrics
kubectl top node my-node
# Show cluster information
kubectl cluster-info
# Dump cluster state to stdout
kubectl cluster-info dump
# Dump cluster state to a directory
kubectl cluster-info dump --output-directory=/path/to/cluster-state
# Apply or replace a taint on a node
kubectl taint nodes foo dedicated=special-user:NoSchedulekubectl set Commands
The kubectl set family lets you modify specific fields of existing resources.
kubectl set resources
# Set CPU limit to 200m and memory to 512Mi for nginx deployment
kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi
# Set both requests and limits
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
# Remove resource limits and requests
kubectl set resources deployment nginx --limits=cpu=0,memory=0 --requests=cpu=0,memory=0kubectl set selector
Sets or replaces the selector of a Service. The selector must start with a letter or digit and be up to 63 characters, containing letters, digits, hyphens, dots, or underscores.
Syntax: selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]
kubectl set image
Updates container images for supported resources such as pods, replication controllers, deployments, daemonsets, jobs, and replicasets.
Syntax: image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 … CONTAINER_NAME_N=CONTAINER_IMAGE_N
# Update nginx container image in a deployment
kubectl set image deployment/nginx nginx=nginx:1.9.1
# Update all deployments and RCs
kubectl set image deployments,rc nginx=nginx:1.9.1 --all
# Update all containers in a daemonset
kubectl set image daemonset abc *=nginx:1.9.1
# Update image from a local file
kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yamlResource Types
The table below lists all supported Kubernetes resource types and their short names.
Formatted Output
Use the -o or --output flag to control the output format of kubectl commands.
Kubectl detailed output and debugging
Increase verbosity with the -v or --v flag followed by an integer level.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
