Top Kubernetes Commands And Tricks For DevOps Tasks

Vinodha kumara
6 min readJun 7, 2024

--

kubectl

This article will help in understanding most important and majorly used Kubernetes commands that would be required for a DevOps Engineer. By mastering these commands, you’ll be equipped to navigate and control Kubernetes clusters effortlessly.

Kubernetes transforms container orchestration, and kubectl is the main tool for managing Kubernetes clusters.

To run these commands, use a Kubernetes cluster or an online cluster, and ensure kubectl is installed.

Let’s dive into the essential kubectl commands:

Fetch kubectl version

Check the client and server version of kubectl.

kubectl version

Get Cluster details

Gather important details about the Kubernetes cluster.

kubectl cluster-info

Listing Available Kubernetes API Resources

In Kubernetes, the api-resources command is used with kubectl to list all top-level API resources available on the cluster's API server.

kubectl api-resources

Retrieving Kubernetes Contexts

List all available contexts (clusters, users, and namespaces) in your kubeconfig file.

kubectl config get-contexts

Switch Clusters

Switch between different contexts/Clusters. This is useful for managing multiple Kubernetes environment.

kubectl config use-context <context_name>

Switch/default Namespace Context

The kubectl config set-context command in Kubernetes allows you to set or change a context in your Kubernetes configuration. A context defines which user, and namespace kubectl commands will use by default. This is useful for managing multiple Kubernetes namespace.

kubectl config set-context --current --namespace <NAMESPACE_NAME>

kubectl apply

Creates or updates Kubernetes resources to match the desired state defined in YAML configuration files.

kubectl apply -f <file_path>

Create Resources Using Kubectl

Create a new resources. For Example here creating namespace

kubectl create namespace <namespace_name>

Patching Kubernetes Resources

Modify the attributes of a resource by applying a strategic merge patch, a JSON merge patch, or a JSON patch. JSON and YAML formats are accepted.

Note: Strategic merge patch is not supported for custom resources.

kubectl patch (-f FILENAME | TYPE NAME) [-p PATCH|--patch-file FILE]

Example:

# Partially update a node using a strategic merge patch, specifying the patch as JSON
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'

# Partially update a node using a strategic merge patch, specifying the patch as YAML
kubectl patch node k8s-node-1 -p $'spec:\n unschedulable: true'

# Partially update a node identified by the type and name specified in "node.json" using strategic merge patch
kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'

# Update a container's image; spec.containers[*].name is required because it's a merge key
kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

# Update a container's image using a JSON patch with positional arrays
kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'

# Update a deployment's replicas through the 'scale' subresource using a merge patch
kubectl patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":{"replicas":2}}'

List Any Resources

List all using kubectl get current namespace.

kubectl get deploy -n kube-system

Manage Deployment

Manage rollouts and updates for Deployments.

Example (Check rollout status for a Deployment):

kubectl rollout status deployment/<deployment_name>

Describe Pod

Get detailed information about a specific pod.

kubectl describe pod <pod_name> -n <NAMESPACE>

Stream logs

Retrieve logs from a running container from pod.

kubectl logs <pod_name> <container_name> -f

Execute command in pod

Execute commands directly inside a container in a pod.

kubectl exec -it <pod_name> -c <container_name> -- /bin/sh

Scale Replicas

Scale the number of replicas for a Deployment, ReplicationController, or StatefulSet. Below Scaling a Deployment to 3 replicas

kubectl scale deployment <deployment_name> --replicas=3

Exposing Kubernetes Resources

Expose a Deployment, ReplicaSet, or Pod as a Service. Here Exposing a Deployment as a NodePort service

kubectl expose deployment <deployment_name> --type=NodePort --port=<port_number>

Delete k8s Resources

Delete a resource defined in a YAML file or directly by name. Delete a pod or any other resources

kubectl delete pod <pod_name>

Setting Node Taints in Kubernetes

Add a taint to a node to restrict the scheduling of certain pods unless they are able to tolerate the taint.

Example (Taint a node with a key=value taint):

kubectl taint nodes <node_name> key=value:taint_effect

Marking a Node as Unschedulable in Kubernetes

Indicate the node as not available for scheduling.

kubectl cordon NODE

kubectl uncordon

Mark node as schedulable. Which was unschedulable using kubectl cordon

kubectl uncordon NODE

Draining a Kubernetes Node

# Drain node "foo", even if there are pods not managed by a replication controller, replica set, job, daemon set, or stateful set on it
kubectl drain foo --force

# As above, but abort if there are pods not managed by a replication controller, replica set, job, daemon set, or stateful set, and use a grace period of 15 minutes
kubectl drain foo --grace-period=900

Explain Resources

Get the documentation for pod manifests

kubectl explain pods

List Events

kubectl get events --sort-by=.metadata.creationTimestamp

Comparing Resource Configurations

Compares the current state of the cluster against the state that the cluster would be in if the manifest was applied.

kubectl diff -f ./my-manifest.yaml

Set Configuring Resources

Rolling update “www” containers of “frontend” deployment, updating the image

kubectl set image deployment/frontend www=image:v2

Replacing Resources in Kubernetes

Force replace, delete and then re-create the resource. Note: Will cause a service outage.

kubectl replace --force -f ./pod.json

Manage Labels

Modify labels by adding, removing, or overwriting them.

kubectl label pods my-pod new-label=awesome                      # Add a Label
kubectl label pods my-pod new-label- # Remove a label
kubectl label pods my-pod new-label=new-value --overwrite # Overwrite an existing value

Editing resources

Edit any API resource in your preferred editor.

kubectl edit svc/docker-registry                      # Edit the service named docker-registry
KUBE_EDITOR="nano" kubectl edit svc/docker-registry # Use an alternative editor

Debug Resources

A debugging pod to troubleshoot an existing pod in Kubernete

kubectl debug my-pod -it --image=busybox:1.28       # Create an interactive debugging session witin existing pod and immediately attach to it
kubectl debug node/my-node -it --image=busybox:1.28 # Create an interactive debugging session on a node and immediately attach to it

Running a Pod

It’s a versatile command that can start a single instance of a container or a set of containers based.

kubectl run -i --tty busybox --image=busybox:1.28 -- sh  # Run pod as interactive shell

Copying files/directories to and from containers

Copy in a remote pod in the current namespace pod.

kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir

Forwarding Ports to Kubernetes Pods

This is useful for accessing cluster services locally without exposing them via a service or ingress. Here’s the syntax:

kubectl port-forward <pod-name> <local-port>:<pod-port>

Viewing Resource Metrics in Kubernetes

It provides an overview of resource consumption by nodes and/or pods within the cluster. Here’s a breakdown of its usage and syntax:

kubectl top [node | pod | container | service] [NAME | -l label]

Formatting output

To output details to your terminal window in a specific format, add the -o (or --output) flag to a supported kubectl command.

-o=custom-columns=<spec> : Print a table using a comma separated list of custom columns.

-o=custom-columns-file=<filename>: Print a table using the custom columns template in the <filename> file

-o=go-template=<template>: Print the fields defined in a golang template

-o=go-template-file=<filename>: Print the fields defined by the golang template in the <filename> file

-o=json: Output a JSON formatted API object

-o=jsonpath=<template>: Print the fields defined in a jsonpath expression

-o=jsonpath-file=<filename>: Print the fields defined by the jsonpath expression in the <filename> file

-o=name: Print only the resource name and nothing else

-o=wide: Output in the plain-text format with any additional information, and for pods, the node name is included

-o=yaml: Output a YAML formatted API object

Examples using -o=custom-columns:

# All images running in a cluster
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'
# All images running in namespace: default, grouped by Pod
kubectl get pods --namespace default --output=custom-columns="NAME:.metadata.name,IMAGE:.spec.containers[*].image"
# All images excluding "registry.k8s.io/coredns:1.6.2"
kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="registry.k8s.io/coredns:1.6.2")].image'
# All fields under metadata regardless of name
kubectl get pods -A -o=custom-columns='DATA:metadata.*'

Kubectl output verbosity and debugging

Kubectl verbosity is set using the -v or --v flags followed by an integer, indicating the log level. Kubernetes logging conventions and levels are detailed here.

--v=0: Generally useful for this to always be visible to a cluster operator.

--v=1: A reasonable default log level if you don't want verbosity.

--v=2: Provides steady state information and key log messages for significant system changes. Recommended default log level.

--v=3: Extended information about changes.

--v=4: Debug level verbosity.

--v=5: Trace level verbosity.

--v=6: Display requested resources.

--v=7: Display HTTP request headers.

--v=8: Display HTTP request contents.

--v=9: Display HTTP request contents without truncation of contents.

Linux Commands and tricks for DevOps tasks read more.

Linux Commands for DevOps CheatSheet read more

Conclusion

Mastering these key kubectl commands equips you to manage Kubernetes clusters efficiently, essential for seamless application deployment, scaling, and ensuring optimal performance. Explore Kubernetes documentation and practice in a test environment to build confidence in managing production clusters. Happy Kubernetting!

If you found this article helpful, please don’t forget to hit the Follow and Clap buttons to help me write more articles like this.
Thank You 🖤

You can contact me on: LinkedIn emailme

--

--

Vinodha kumara

DevSecOps, MLOps, Cloud Computing, DE, ML, DL, Programmer, Blogger, Volunteer