Mastering kubectl: Essential Commands for Kubernetes Operations
This guide provides a comprehensive overview of kubectl, covering autocomplete setup, context and configuration management, creating, viewing, updating, patching, editing, scaling, and deleting resources, as well as interacting with pods, nodes, and clusters, plus advanced set commands and output formatting for effective Kubernetes operations.
Kubectl Common Commands Guide
Kubectl is the most direct way to operate a Kubernetes cluster, especially for operations personnel who need detailed mastery of these commands.
Kubectl Autocomplete
# setup autocomplete in bash, bash-completion package should be installed first.</code>
<code>$ source <(kubectl completion bash)</code>
<code># setup autocomplete in zsh</code>
<code>$ source <(kubectl completion zsh)Kubectl Context and Configuration
Set the Kubernetes cluster for kubectl interactions and modify configuration information. Refer to the kubeconfig file documentation for detailed information.
# Show merged kubeconfig</code>
<code>$ kubectl config view</code>
<code># Use multiple kubeconfig files and view merged config</code>
<code>$ KUBECONFIG=~/.kube/config:~/.kube/kubconfig2 kubectl config view</code>
<code># Get password for e2e user</code>
<code>$ kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'</code>
<code># Show current context</code>
<code>$ kubectl config current-context</code>
<code># Set default context</code>
<code>$ kubectl config use-context my-cluster-name</code>
<code># Add a new cluster with basic authentication</code>
<code>$ kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword</code>
<code># Set context with specific user and namespace</code>
<code>$ kubectl config set-context gce --user=cluster-admin --namespace=foo && kubectl config use-context gceCreate Objects
Kubernetes manifests can be defined in JSON or YAML format, using the extensions .yaml, .yml, or .json.
# Create resources</code>
<code>$ kubectl create -f ./my-manifest.yaml</code>
<code># Create resources from multiple files</code>
<code>$ kubectl create -f ./my1.yaml -f ./my2.yaml</code>
<code># Create resources from all manifests in a directory</code>
<code>$ kubectl create -f ./dir</code>
<code># Create resources from a URL</code>
<code>$ kubectl create -f https://git.io/vPieo</code>
<code># Run an nginx instance</code>
<code>$ kubectl run nginx --image=nginx</code>
<code># Get documentation for pods and services</code>
<code>$ kubectl explain pods,svc</code>
<code># Create multiple YAML objects from stdin</code>
<code>$ 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</code>
<code># Create a Secret with several keys</code>
<code>$ cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: $(echo "s33msi4" | base64)
username: $(echo "jane" | base64)
EOFShow and Find Resources
# List all services in all namespaces</code>
<code>$ kubectl get services</code>
<code># List all pods in all namespaces</code>
<code>$ kubectl get pods --all-namespaces</code>
<code># List pods with wide output</code>
<code>$ kubectl get pods -o wide</code>
<code># Get a specific deployment</code>
<code>$ kubectl get deployment my-dep</code>
<code># Include uninitialized pods</code>
<code>$ kubectl get pods --include-uninitialized</code>
<code># Describe nodes and pods</code>
<code>$ kubectl describe nodes my-node</code>
<code>$ kubectl describe pods my-pod</code>
<code># List services sorted by name</code>
<code>$ kubectl get services --sort-by=.metadata.name</code>
<code># Sort pods by restart count</code>
<code>$ kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'</code>
<code># Get version label of pods with app=cassandra</code>
<code>$ kubectl get pods --selector=app=cassandra -o jsonpath='{.items[*].metadata.labels.version}'</code>
<code># Get ExternalIP of all nodes</code>
<code>$ kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'</code>
<code># List pod names belonging to a specific replication controller (example uses jq)</code>
<code>$ 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})</code>
<code># Show which nodes are ready</code>
<code>$ JSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}' && kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"</code>
<code># List Secrets used by current pods</code>
<code>$ kubectl get pods -o json | jq '.items[].spec.containers[].env[]?.valueFrom.secretKeyRef.name' | grep -v null | sort | uniqUpdate Resources
$ kubectl rolling-update frontend-v1 -f frontend-v2.json # Rolling update pod frontend-v1</code>
<code>$ kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2 # Update resource name and image</code>
<code>$ kubectl rolling-update frontend --image=image:v2 # Update image in frontend pod</code>
<code>$ kubectl rolling-update frontend-v1 frontend-v2 --rollback # Roll back ongoing update</code>
<code>$ cat pod.json | kubectl replace -f - # Replace pod from stdin JSON</code>
<code># Force replace (deletes then recreates, causing service interruption)</code>
<code>$ kubectl replace --force -f ./pod.json</code>
<code># Expose RC nginx on port 80 mapping to container port 8000</code>
<code>$ kubectl expose rc nginx --port=80 --target-port=8000</code>
<code># Update image tag of a single‑container pod to v4</code>
<code>$ kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -</code>
<code># Add a label</code>
<code>$ kubectl label pods my-pod new-label=awesome</code>
<code># Add an annotation</code>
<code>$ kubectl annotate pods my-pod icon-url=http://goo.gl/XXBTWq</code>
<code># Autoscale deployment "foo"</code>
<code>$ kubectl autoscale deployment foo --min=2 --max=10Patch Resources
Use strategic merge patches to modify resources.
# Partially update a node</code>
<code>kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'</code>
<code># Update container image in a pod (name is required for merge key)</code>
<code>$ kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'</code>
<code># JSON patch to update container image</code>
<code>$ kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'</code>
<code># JSON patch to remove livenessProbe from a deployment</code>
<code>$ kubectl patch deployment valid-deployment --type json -p='[{"op": "remove", "path": "/spec/template/spec/containers/0/livenessProbe"}]'Edit Resources
Edit any API resource in your preferred editor.
# Edit service named docker-registry</code>
<code>$ kubectl edit svc/docker-registry</code>
<code># Use a different editor</code>
<code>$ KUBE_EDITOR="nano" kubectl edit svc/docker-registryScale Resources
# Scale a replicaset named 'foo' to 3</code>
<code>$ kubectl scale --replicas=3 rs/foo</code>
<code># Scale a resource defined in foo.yaml to 3</code>
<code>$ kubectl scale --replicas=3 -f foo.yaml</code>
<code># Scale deployment mysql from 2 to 3 replicas</code>
<code>$ kubectl scale --current-replicas=2 --replicas=3 deployment/mysql</code>
<code># Scale multiple replication controllers</code>
<code>$ kubectl scale --replicas=5 rc/foo rc/bar rc/bazDelete Resources
# Delete resources defined in pod.json</code>
<code>$ kubectl delete -f ./pod.json</code>
<code># Delete a pod and a service</code>
<code>$ kubectl delete pod,service baz foo</code>
<code># Delete pods and services with a label</code>
<code>$ kubectl delete pods,services -l name=myLabel</code>
<code># Include uninitialized resources</code>
<code>$ kubectl delete pods,services -l name=myLabel --include-uninitialized</code>
<code># Delete all pods and services in a namespace</code>
<code>$ kubectl -n my-ns delete po,svc --allInteract with Running Pods
# Show pod logs</code>
<code>$ kubectl logs my-pod</code>
<code># Show logs of a specific container</code>
<code>$ kubectl logs my-pod -c my-container</code>
<code># Stream pod logs</code>
<code>$ kubectl logs -f my-pod</code>
<code># Run an interactive shell in a pod</code>
<code>$ kubectl run -i --tty busybox --image=busybox -- sh</code>
<code># Attach to a running container</code>
<code>$ kubectl attach my-pod -i</code>
<code># Port‑forward pod port 6000 to local 5000</code>
<code>$ kubectl port-forward my-pod 5000:6000</code>
<code># Execute a command in a pod (single‑container case)</code>
<code>$ kubectl exec my-pod -- ls /</code>
<code># Execute a command in a specific container</code>
<code>$ kubectl exec my-pod -c my-container -- ls /</code>
<code># Show metrics for a pod and its containers</code>
<code>$ kubectl top pod POD_NAME --containersInteract with Nodes and Cluster
# Mark node unschedulable</code>
<code>$ kubectl cordon my-node</code>
<code># Drain node for maintenance</code>
<code>$ kubectl drain my-node</code>
<code># Mark node schedulable again</code>
<code>$ kubectl uncordon my-node</code>
<code># Show node metrics</code>
<code>$ kubectl top node my-node</code>
<code># Show cluster info</code>
<code>$ kubectl cluster-info</code>
<code># Dump cluster state to stdout</code>
<code>$ kubectl cluster-info dump</code>
<code># Dump cluster state to a directory</code>
<code>$ kubectl cluster-info dump --output-directory=/path/to/cluster-state</code>
<code># Update or add a taint</code>
<code>$ kubectl taint nodes foo dedicated=special-user:NoSchedulekubectl set Command
The kubectl set family configures specific resources or modifies existing ones.
kubectl set resources
This command sets resource limits and requests for containers.
# Set CPU limit to 200m and memory to 512Mi for nginx container in a deployment</code>
<code>$ kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi</code>
<code># Set both limits and requests</code>
<code>$ kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi</code>
<code># Remove resource specifications</code>
<code>$ kubectl set resources deployment nginx --limits=cpu=0,memory=0 --requests=cpu=0,memory=0kubectl set selector
Sets the selector for a resource; existing selectors are overwritten.
Syntax: selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]
kubectl set image
Updates the container image of existing resources. Supported resource types include pod, replicationcontroller, deployment, daemonset, job, and replicaset.
# Set nginx container image to nginx:1.9.1 in a deployment</code>
<code>$ kubectl set image deployment/nginx nginx=nginx:1.9.1</code>
<code># Update all deployments and RCs</code>
<code>$ kubectl set image deployments,rc nginx=nginx:1.9.1 --all</code>
<code># Update all containers in a daemonset</code>
<code>$ kubectl set image daemonset abc *=nginx:1.9.1</code>
<code># Update image from a local file</code>
<code>$ 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 aliases.
Formatted Output
To output detailed information in a specific format, add the -o or --output flag to the kubectl command.
Kubectl Detailed Output and Debugging
Use the -v or --v flag followed by an integer to set the log verbosity 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.
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.
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.
