Cloud Native 15 min read

Master Essential kubectl Commands: A Practical Guide for Kubernetes Ops

This comprehensive guide covers kubectl autocomplete, context configuration, object creation, resource viewing, updating, patching, editing, scaling, deletion, pod and node interaction, as well as the versatile kubectl set commands, formatted output options, and visual references for effective Kubernetes cluster management.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Essential kubectl Commands: A Practical Guide for Kubernetes Ops

kubectl Common Commands Guide

Kubectl is the primary command‑line tool for interacting with a Kubernetes cluster; operators need a thorough grasp of its commands.

Kubectl Autocomplete

# setup autocomplete in bash (bash‑completion required)
source <(kubectl completion bash)
# setup autocomplete in zsh
source <(kubectl completion zsh)

Contexts and Configuration

Configure the cluster context and modify kubeconfig. See “Using kubeconfig for cross‑cluster authentication” for details.

# Show merged kubeconfig
kubectl config view
# Use multiple kubeconfig files
KUBECONFIG=~/.kube/config:~/ .kube/kubconfig2 kubectl config view
# Get password of 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 credentials
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
# Set context with user and namespace
kubectl config set-context gce --user=cluster-admin --namespace=foo && kubectl config use-context gce

Creating Objects

Manifest files can be JSON or YAML (.yaml, .yml, .json).

# Create resources from a file
kubectl create -f ./my-manifest.yaml
# Create from multiple files
kubectl create -f ./my1.yaml -f ./my2.yaml
# Create from a directory
kubectl create -f ./dir
# Create from a URL
kubectl create -f https://git.io/vPieo
# Run an nginx pod
kubectl run nginx --image=nginx
# Explain resources
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 keys
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: $(echo "s33msi4" | base64)
  username: $(echo "jane" | base64)
EOF

Viewing and Finding Resources

# List all services in all namespaces
kubectl get services --all-namespaces
# List all pods in all namespaces
kubectl get pods --all-namespaces
# Show pods with wide output
kubectl get pods -o wide
# Describe a node
kubectl describe nodes my-node
# Sort services 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 secrets used by current pods
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq

Updating Resources

# Rolling update a deployment
kubectl rolling-update frontend-v1 -f frontend-v2.json
kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2
kubectl rolling-update frontend --image=image:v2
kubectl rolling-update frontend-v1 frontend-v2 --rollback
# Replace a pod from stdin
cat pod.json | kubectl replace -f -
# Force replace (service interruption)
kubectl replace --force -f ./pod.json
# Expose a RC as a service
kubectl expose rc nginx --port=80 --target-port=8000
# Patch a node
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
# Patch a pod image
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
# JSON patch example
kubectl patch pod valid-pod --type='json' -p='[{"op":"replace","path":"/spec/containers/0/image","value":"new image"}]'

Editing Resources

# Edit a service
kubectl edit svc/docker-registry
# Use a different editor
KUBE_EDITOR="nano" kubectl edit svc/docker-registry

Scaling Resources

# Scale a replicaset to 3
kubectl scale --replicas=3 rs/foo
# Scale using a yaml file
kubectl scale --replicas=3 -f foo.yaml
# Scale a deployment from 2 to 3
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
# Scale multiple RCs
kubectl scale --replicas=5 rc/foo rc/bar rc/baz

Deleting Resources

# Delete resources defined in a file
kubectl delete -f ./pod.json
# Delete specific pod and service
kubectl delete pod,service baz foo
# Delete by label
kubectl delete pods,services -l name=myLabel
# Delete with uninitialized flag
kubectl delete pods,services -l name=myLabel --include-uninitialized
# Delete all pods and services in a namespace
kubectl -n my-ns delete po,svc --all

Interacting with Running Pods

# View pod logs
kubectl logs my-pod
kubectl logs my-pod -c my-container
kubectl logs -f my-pod
kubectl logs -f my-pod -c my-container
# Run an interactive shell
kubectl run -i --tty busybox --image=busybox -- sh
# Attach to a container
kubectl attach my-pod -i
# Port‑forward
kubectl port-forward my-pod 5000:6000
# Execute a command in a container
kubectl exec my-pod -- ls /
kubectl exec my-pod -c my-container -- ls /
# Show pod metrics
kubectl top pod POD_NAME --containers

Node and Cluster Interaction

# Mark node unschedulable
kubectl cordon my-node
# Drain node for maintenance
kubectl drain my-node
# Mark node schedulable again
kubectl uncordon my-node
# Show node metrics
kubectl top node my-node
# Cluster info
kubectl cluster-info
# Dump cluster state
kubectl cluster-info dump
kubectl cluster-info dump --output-directory=/path/to/cluster-state
# Taint a node
kubectl taint nodes foo dedicated=special-user:NoSchedule

kubectl set Commands

The kubectl set family modifies resources such as environment variables, images, resources, selectors, and service accounts.

kubectl set resources

Sets CPU and memory limits/requests for Pods. If limits are set without requests, requests default to the limit value.

# Set CPU limit to 200m and memory to 512Mi for deployment nginx
kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi
# Set both limits and requests
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
# Remove resource constraints
kubectl set resources deployment nginx --limits=cpu=0,memory=0 --requests=cpu=0,memory=0

kubectl set selector

Assigns a selector to a resource; existing selectors are overwritten. Currently only works for Service objects.

kubectl set selector service my-svc app=frontend

kubectl set image

Updates container images for supported resources (pods, RCs, deployments, daemonsets, jobs, replicasets).

# 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

Resource Types

The table below lists all Kubernetes resource types and their short aliases.

Formatted Output

Use -o or --output with kubectl to specify the output format (json, yaml, wide, etc.).

Kubectl detailed output and debugging

Use -v or --v followed by an integer to set the log verbosity level.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cloud-nativeOperationsKuberneteskubectlcommand-line
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.