Cloud Native 17 min read

Master Essential kubectl Commands for Efficient Kubernetes Management

This comprehensive guide covers kubectl autocomplete setup, context and configuration handling, creating, retrieving, updating, patching, editing, scaling, and deleting resources, interacting with pods and nodes, as well as advanced "kubectl set" commands, resource types, and output formatting for effective Kubernetes cluster operations.

Efficient Ops
Efficient Ops
Efficient Ops
Master Essential kubectl Commands for Efficient Kubernetes Management

kubectl Common Commands Guide

kubectl is the primary command‑line tool for interacting with a Kubernetes cluster; operators need to master its commands for efficient cluster management.

Kubectl Autocomplete

<code># setup autocomplete in bash (bash‑completion package required)
source <(kubectl completion bash)
# setup autocomplete in zsh
source <(kubectl completion zsh)</code>

Kubectl Context and Configuration

View merged kubeconfig, use multiple config files, query specific fields, switch contexts, and set credentials.

<code># 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 basic‑auth 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</code>

Create Objects

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

kubectl create

with files, directories, URLs, or stdin.

<code># Create from a manifest file
kubectl create -f ./my-manifest.yaml
# Create from multiple files
kubectl create -f ./my1.yaml -f ./my2.yaml
# Create from all files in 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 literal values
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Secret
metadata:
  name: mysecret
type: Opaque
data:
  password: $(echo "s33msi4" | base64)
  username: $(echo "jane" | base64)
EOF</code>

Display and Find Resources

<code># List all services
kubectl get services
# List all pods in all namespaces
kubectl get pods --all-namespaces
# Show 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 a node or pod
kubectl describe nodes my-node
kubectl describe pods my-pod
# 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 label values via jsonpath
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 pods using a specific Secret
kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniq</code>

Update Resources

<code># 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 resource from stdin
cat pod.json | kubectl replace -f -
# Force replace (deletes then recreates)
kubectl replace --force -f ./pod.json
# Expose a replication controller as a service
kubectl expose rc nginx --port=80 --target-port=8000
# Update image tag in a pod definition
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
# Add a label
kubectl label pods my-pod new-label=awesome
# Add an annotation
kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq
# Autoscale a deployment
kubectl autoscale deployment foo --min=2 --max=10</code>

Patch Resources

<code># Patch a node to be unschedulable
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
# Patch a pod's container image (merge patch)
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'
# JSON patch to change 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"}]'</code>

Edit Resources

<code># Edit a service with default editor
kubectl edit svc/docker-registry
# Use a specific editor (nano)
KUBE_EDITOR="nano" kubectl edit svc/docker-registry</code>

Scale Resources

<code># Scale a replicaset
kubectl scale --replicas=3 rs/foo
# Scale from a manifest 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/baz</code>

Delete Resources

<code># 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 including uninitialized
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</code>

Interact with Running Pods

<code># Show pod logs
kubectl logs my-pod
# Show container logs
kubectl logs my-pod -c my-container
# Stream 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
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 metrics for a pod
kubectl top pod POD_NAME --containers</code>

Interact with Nodes and Cluster

<code># 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</code>

kubectl set Command

The

kubectl set

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

kubectl set resources

<code># Set CPU limit and memory for a deployment's nginx container
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
kubectl set resources deployment nginx --limits=cpu=0,memory=0 --requests=cpu=0,memory=0</code>

kubectl set selector

Sets or replaces the selector of a resource (currently only Service).

<code># Set selector (must start with a letter or number, max 63 chars)
kubectl set selector svc/my-service app=frontend --resource-version=12345</code>

kubectl set image

<code># Update image of a deployment's container
kubectl set image deployment/nginx nginx=nginx:1.9.1
# Update all deployments and replication controllers
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 (local mode)
kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml</code>

Resource Types

The table below lists all supported Kubernetes resource kinds and their short names.

Formatting Output

Use

-o

or

--output

to specify output format (json, yaml, wide, etc.). Increase verbosity with

-v

or

--v

followed by an integer.

Kubectl detailed output and debugging

clicloud nativeoperationsKuberneteskubectl
Efficient Ops
Written by

Efficient Ops

This public account is maintained by Xiaotianguo and friends, regularly publishing widely-read original technical articles. We focus on operations transformation and accompany you throughout your operations career, growing together happily.

0 followers
Reader feedback

How this landed with the community

login 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.